'How to merge an arrays of objects js
everyone! I'm doing the project right now and I need some help with the following problem: I have to merge 2 arrays of objects:
- an array, where each object contains a user id
- an array, where each object contains information about a user
How can i merge them? I need to compare ids in each object in both arrays and if ids match I need to push the object fron the second array into the object from the first array. So as a result, I need 1 array of objects, where each object contains in itself information about a user from the second object.
an object from a first array looks something like this:
{
1. country_id: null
2. created_at: "2020-11-13T04:30:16.000000Z"
3. id: 1
4. updated_at: "2020-11-13T04:30:16.000000Z"
}
an object from second array looks like this:
{
1. country_id: null
2. created_at: "2020-11-13T04:30:16.000000Z"
3. id: 1
4. name: "1111"
5. photo: null
6. surname: "111"
7. updated_at: "2020-11-13T04:30:16.000000Z"
}
Can anyone help me solve this, please?
Solution 1:[1]
Pretty simple if you use ES2018
const resultArray = arr1.map(t1 => ({...t1, ...arr2.find(t2 => t2.id === t1.id)}))
Solution 2:[2]
You can convert one array into an object and then iterate over the other to combine both. This way you can have O(n) time complexity.
const arr1 = [
{
"country_id": null,
"created_at": "2020-11-13T04:30:16.000000Z",
"id": 1,
"updated_at": "2020-11-13T04:30:16.000000Z"
}
];
const arr2 = [
{
"country_id": null,
"created_at": "2020-11-13T04:30:16.000000Z",
"id": 1,
"name": "1111",
"photo": null,
"surname": "111",
"updated_at": "2020-11-13T04:30:16.000000Z"
}
];
const dictionary = arr2.reduce((acc, curr) => ({
...acc,
...(curr.id && { [curr.id]: curr })
}), {});
const mappedArray = arr1
.map(itemFromFirst => ({
...itemFromFirst, ...dictionary[itemFromFirst.id]
})
);
/* Result:
[{
"country_id": null,
"created_at": "2020-11-13T04:30:16.000000Z",
"id": 1,
"updated_at": "2020-11-13T04:30:16.000000Z",
"name": "1111",
"photo": null,
"surname": "111"
}]
*/
Solution 3:[3]
Run a loop over first array, picking id for each object.
Then filter the second array based on id; use object spreader to merge the objects.
function mergeOnId(array1, array2) {
// assuming both the array contain only one object with same id, each.
var out = []
for(let i = 0; i < array1.length; i++) {
for(let j = 0; j < array2.length; j++) {
if(array1[i].id === array2[j].id) {
out.push({ ...array1[i], ...array2[j] })
break;
}
}
}
return out
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | smtaha512 |
| Solution 3 | Anubhav |
