想合并数组的对象。
var arr1 = [
{nested: {first: "aaa"}},
{nested: {first: "bbb"}},
{nested: {first: "ccc"}}
];
var arr2 = [
{nested: {last: "zzz"}},
{nested: {last: "yyy"}}
];
一直试图合并这种方式无济于事:
arr1.map((item, i) => {
return Object.assign({},
{firstName: item.nested.first},
{lastName: arr2[i].nested.last})
})
想要这样:
[
{first: "aaa", last: "zzz"},
{first: "bbb", last: "yyy"}
{first: "ccc"}
];
最佳答案
您必须迭代并将值映射回以合并数组中的每个对象
var arr1 = [
{nested: {first: "aaa"}},
{nested: {first: "bbb"}},
{nested: {first: "ccc"}}
];
var arr2 = [
{nested: {last: "zzz"}},
{nested: {last: "yyy"}}
];
var arr3 = arr1.map( (obj,index) => {
return Object.assign({}, obj.nested, arr2[index] && arr2[index].nested||{});
});
console.log(arr3)
请注意,这假设第一个数组比第二个长,如果没有给定,您必须检查长度并从长度最大的数组开始。
关于javascript - 合并嵌套的两个数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40348741/