How to Merge Objects in JavaScript
Need to combine properties from two or more objects into a single object? Merging objects in JavaScript is a common requirement.
There are multiple ways to achieve this, but I'll share the two simplest ways:
The Spread Operator
Introduced in ES6, the spread operator is a concise and popular way to merge objects.
const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = { ...object1, ...object2 }; console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
Caution: Order matters
When properties overlap (like b
in this example), the property from the last object specified in the merge (in this case, object2
) will take precedence.
Using Object.assign()
This method copies all enumerable properties from one or more source objects to a target object and returns the target object.
const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = Object.assign({}, object1, object2); console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
The first argument ({}
in the example) is the target object into which the source objects will be merged. This ensures that object1
and object2
are not modified.
Again Order Matters
Similar to the spread operator, if properties have the same key, the last one will overwrite the earlier ones.