我有两个数组:
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' } ];
如何摆脱中间的花括号,使它成为一个物体?
答案 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);