Marcos Belunti Marcos Belunti - 2 months ago 9
Javascript Question

Javascript merge 2 arrays into a 3rd array to get all data required

I have 2 separate arrays which I need to merge into a third one so I can get all the data required.
Basically the 1st array has an id, and name and in order to get the address I need to search inside the 2nd array and match the id's so I can have all the data from the person.

Here is the data and code:

//Array 1
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"},{"id":"456","name":"name 2"}]}];

//Array 2
var myPersonArray = [{"person":[{"id":"123","address":"address 1"},{"id":"456","address":"address 2"}]}];

var arrayLength = myPeopleArray[0].people.length;

for (var i = 0; i < arrayLength; i++) {

console.log("id: " + myPeopleArray[0].people[i].id);

}

//Wanted Result:

[{"people":[

{
"id":"123",
"name":"name 1",
"address":"address 1"
},

{
"id":"456",
"name":"name 2",
"address":"address 2"
}
]

}]


How can I do this?

Answer

You could iterate both arrays and build new object with the joined properties.

var myPeopleArray = [{ "people": [{ "id": "123", "name": "name 1" }, { "id": "456", "name": "name 2" }] }],
    myPersonArray = [{ "person": [{ "id": "123", "address": "address 1" }, { "id": "456", "address": "address 2" }] }],
    hash = Object.create(null),
    joined = [],
    joinById = function (o) {
        if (!(o.id in hash)) {
            hash[o.id] = {};
            joined.push(hash[o.id]);
        }
        Object.keys(o).forEach(function (k) {
            hash[o.id][k] = o[k];
        });
    };

myPeopleArray[0].people.forEach(joinById);
myPersonArray[0].person.forEach(joinById);

console.log(joined);