javascript-如何通过索引合并数组中的每个对象?
作者:互联网
如何合并两个相同长度的对象数组?
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如果它们共享相同的键,则它们将覆盖这些值,否则将添加到基础数组中.合并应该按照对象在每个数组中出现的顺序顺序进行.
在此示例中,数组包含两个对象,但是对于我的实际情况,我有几十个对象.
这是我一直在尝试的操作,但这只会合并第一组对象:
var array3 = Object.assign(array1[0], array2[0]);
如何遍历或映射?
解决方法:
一个简单的map
和Object.assign
就可以了.将其分配给新的空对象,以避免使现有对象发生变异.
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);
如果您有未知数量的数组,例如:
const arrays = [
array1,
array2,
array3,
// …
];
那么您可以使用这种方法:
const mergedArray = Array.from({
length: arrays[0].length
}, (_, index) => Object.assign({}, ...arrays.map(({[index]: obj}) => obj))));
通过以下示例查看此操作:
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))));
标签:javascript,arrays,javascript-objects 来源: https://codeday.me/bug/20191012/1901213.html