Sometimes, we want to merge two array of objects based on a key with JavaScript.
In this article, we’ll look at how to merge two array of objects based on a key with JavaScript.
How to merge two array of objects based on a key with JavaScript?
To merge two array of objects based on a key with JavaScript, we can use the array map and find methods and the spread operator.
For instance, we write
const arr1 = [
{ id: "abdc4051", date: "2017-01-24" },
{ id: "abdc4052", date: "2017-01-22" },
];
const arr2 = [
{ id: "abdc4051", name: "ab" },
{ id: "abdc4052", name: "abc" },
];
const mergeById = (a1, a2) =>
a1.map((itm) => ({
...a2.find((item) => item.id === itm.id && item),
...itm,
}));
console.log(mergeById(arr1, arr2));
to define the mergeById function.
In it, we call a1.map with a callback that has the contents of the object in a2 that has the same id of the current object in a1, which is itm and the itm object.
We find the object with the same id value as the one being looped through in a1 with
a2.find((item) => item.id === itm.id && item)
We spread the properties of each into a new object and return it.
Conclusion
To merge two array of objects based on a key with JavaScript, we can use the array map and find methods and the spread operator.