Use the map function or push() method with a loop to merge an array of objects by key in JavaScript.
- Map over array1
- Search through array2 for array1.id
- If you find it …spread the result of array2 into array1
The final array will only contain id’s that matches both arrays
Merge an array of objects by key in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
let arr1 = [
{ id: "abc1", date: "2017-01-24" },
{ id: "abc2", date: "2017-01-22" }
];
let arr2 = [
{ id: "abc3", name: "John" },
{ id: "abc4", name: "Tim" }
];
let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));
console.log(arr3);
</script>
</body>
</html>
Output:
Use the below code if arr1
and arr2
are in a different order:
let merged = [];
for(let i=0; i<arr1.length; i++) {
merged.push({
...arr1[i],
...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}
);
}
console.log(merged);
Use this if arr1
and arr2
are in the same order
let merged = [];
for(let i=0; i<arr1.length; i++) {
merged.push({
...arr1[i],
...arr2[i]
});
}
console.log(merged);
Source: stackoverflow.com
Do comment if you have any doubts or suggestions on this JS Merge array code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version