将2个对象数组合并为1

时间:2017-06-19 15:00:54

标签: javascript arrays

我有两个数组:

var arr1 = [ { id: 137, surname: 'Smith', name: 'John', avg: 14.5 }];

var arr2 = [{ subject: 'Maths', code: 'IPSE507'} ];

我想加入他们,以便我有

var arr3 = [ { id: 137, surname: 'Smith', name: 'John', avg: 14.5, subject: 'Maths', code: 'IPSE507'} ];

但当我Array.prototype.push.apply(arr1, arr2)时,我得到了:

var arr3 = [ { id: 137, surname: 'Smith', name: 'John', avg: 5.5 }, { subject: 'Maths', code: 'IPSE507' } ];

如何摆脱中间的花括号,使它成为一个物体?

1 个答案:

答案 0 :(得分:2)

使用Array.map迭代它们。之后,只需使用Object.assign函数指定适当的属性。

请注意,它需要使用索引

var arr1 = [ { id: 137, surname: 'Smith', name: 'John', avg: 14.5 }];

var arr2 = [{ subject: 'Maths', code: 'IPSE507'} ];

var newArr = arr1.map((item, index) => (Object.assign({},item, arr2[index])));

console.log(newArr);