Ask any question about JavaScript here... and get an instant response.
How can I merge two arrays of objects by a unique key in JavaScript while preserving all properties?
Asked on Oct 22, 2025
Answer
To merge two arrays of objects by a unique key in JavaScript while preserving all properties, you can use the "map" and "reduce" methods. This approach ensures that objects with the same key are combined into a single object.
<!-- BEGIN COPY / PASTE -->
const array1 = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
const array2 = [
{ id: 1, age: 25 },
{ id: 3, name: "Charlie" }
];
const mergedArray = [...array1, ...array2].reduce((acc, obj) => {
const existing = acc.find(item => item.id === obj.id);
if (existing) {
Object.assign(existing, obj);
} else {
acc.push(obj);
}
return acc;
}, []);
console.log(mergedArray);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This code uses the "reduce" method to iterate over the combined arrays.
- The "find" method checks if an object with the same "id" already exists in the accumulator.
- "Object.assign" merges properties of objects with the same "id".
- The result is an array where objects with the same "id" are merged, preserving all properties.
Recommended Links:
