Julio Cornelio
Julio Cornelio

Reputation: 171

merge the object of two arrays which are nested

would like to merge the objects of arrays.

var arr1 = [
    {nested: {first: "aaa"}},
    {nested: {first: "bbb"}},
    {nested: {first: "ccc"}}
];
var arr2 = [
    {nested: {last: "zzz"}},
    {nested: {last: "yyy"}}
];

been trying to merge this way to no avail:

arr1.map((item, i) => {
    return Object.assign({}, 
    {firstName: item.nested.first},
    {lastName: arr2[i].nested.last}) 
})

would like this:

[
    {first: "aaa", last: "zzz"},
    {first: "bbb", last: "yyy"}
    {first: "ccc"}
];

Upvotes: 1

Views: 37

Answers (1)

adeneo
adeneo

Reputation: 318262

You'll have to iterate and map the values back to merge each object in the arrays

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)

Note that this assumes the first array is longer than the second, if that's not a given, you'd have to check the length and start with the array with the greatest length.

Upvotes: 3

Related Questions