如何通过索引合并数组中的每个对象? [英] How to merge each object within arrays by index?

查看:132
本文介绍了如何通过索引合并数组中的每个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并两个相同长度的对象数组?

How can I merge two arrays of objects of same length?

var array1 = [
  {name: "lang", value: "English"}, 
  {name: "age", value: "18"}
];
var array2 = [
  {code: "EN", text: "English language"}, 
  {code: "DE", value: "German", text: "German language"}
];

目标是创建以下数组:

var array3 = [
  {name: "lang", value: "English", code: "EN", text: "English language"}, 
  {name: "age", code: "DE", value: "German", text: "German language"}
];

想法是创建一个新数组,其中 array1 是基数,如果 array2 共享相同的键,则它们将覆盖值,否则将添加到基数数组中。合并应该按照对象在每个数组中出现的顺序顺序进行。

The idea is to create a new array in which array1 is the base and array2 overrides the values if they share the same key, and otherwise adds to the base array. The merging should happen sequentially in the same order that the objects appear in each array.

在此示例中,数组包含两个对象,但是对于我的实际情况,我有几十个对象。

In this example, the arrays contains two objects, but for my actual situation, I have a couple of dozens of objects.

这是我一直在尝试做的事情,但这仅合并了第一组对象:

This is what I’ve been trying to do, but this only merges the first set of objects:

var array3 = Object.assign(array1[0], array2[0]);

如何遍历或映射?

推荐答案

一个简单的 地图 Object.assign 即可。分配给一个新的空对象,以避免变异现有对象。

A simple map with an Object.assign will do it. Assign unto a new empty object in order to avoid mutating the existing objects.

var array1 = [
  {name: "lang", value: "English"}, 
  {name: "age", value: "18"}
];
var array2 = [
  {code: "EN", text: "English language"}, 
  {code: "DE", value: "German", text: "German language"}
];

var array3 = array1.map((obj, index) => Object.assign({}, obj, array2[index]));

console.log(array3);

如果您有未知数量的数组,例如:

If you have an unknown number of arrays like this:

const arrays = [
  array1,
  array2,
  array3,
  // …
];

然后您可以使用以下方法:

then you can use this approach:

const mergedArray = Array.from({
  length: arrays[0].length
}, (_, index) => Object.assign({}, ...arrays.map(({[index]: obj}) => obj))));

请参见以下示例,进行操作:

See this in action with the following example:

const arrays = [
  [
    {a: 3, b: 5},
    {a: 7, b: 2},
    {a: 1}
  ],
  [
    {b: 8, c: 42},
    {a: 1, b: 12, c: 44},
    {b: 0}
  ],
  [
    {d: 14, e: 15},
    {d: 7},
    {a: 10}
  ]
];

console.log(Array.from({
  length: arrays[0].length
}, (_, index) => Object.assign({}, ...arrays.map(({[index]: obj}) => obj))));

这篇关于如何通过索引合并数组中的每个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆