How to Merge Two Objects in JavaScript: Simple Methods Explained
You can merge two objects in JavaScript using the
spread operator like {...obj1, ...obj2} or the Object.assign() method. Both combine properties from multiple objects into one, with later properties overwriting earlier ones if keys match.Syntax
There are two common ways to merge objects:
- Spread operator:
{...obj1, ...obj2}creates a new object combining properties fromobj1andobj2. - Object.assign():
Object.assign(target, source1, source2)copies properties from source objects into the target object.
In both, if keys overlap, the value from the later object overwrites the earlier one.
javascript
const merged = {...obj1, ...obj2}; // or const merged = Object.assign({}, obj1, obj2);
Example
This example shows merging two objects with overlapping keys. The second object's values overwrite the first's for matching keys.
javascript
const obj1 = {a: 1, b: 2}; const obj2 = {b: 3, c: 4}; const mergedWithSpread = {...obj1, ...obj2}; console.log('Merged with spread:', mergedWithSpread); const mergedWithAssign = Object.assign({}, obj1, obj2); console.log('Merged with Object.assign:', mergedWithAssign);
Output
Merged with spread: { a: 1, b: 3, c: 4 }
Merged with Object.assign: { a: 1, b: 3, c: 4 }
Common Pitfalls
Common mistakes when merging objects include:
- Modifying the original objects unintentionally when using
Object.assign()without an empty target object. - Expecting deep merge behavior; both methods only do shallow merges, so nested objects are not merged but replaced.
Here is an example showing the wrong and right way:
javascript
// Wrong: modifies obj1 const obj1 = {a: 1}; const obj2 = {b: 2}; Object.assign(obj1, obj2); console.log(obj1); // obj1 is changed // Right: create new object const merged = Object.assign({}, obj1, obj2); console.log(merged); // obj1 stays unchanged
Output
{ a: 1, b: 2 }
{ a: 1, b: 2 }
Quick Reference
Summary tips for merging objects:
- Use
{...obj1, ...obj2}for a clean, modern syntax. - Use
Object.assign({}, obj1, obj2)to avoid modifying original objects. - Both methods do shallow merges only.
- Later object properties overwrite earlier ones if keys match.
Key Takeaways
Use the spread operator {...obj1, ...obj2} for simple and readable object merging.
Object.assign({}, obj1, obj2) merges without changing the original objects.
Both methods perform shallow merges; nested objects are replaced, not merged.
If keys overlap, the value from the later object overwrites the earlier one.
Avoid modifying original objects unless intentional by using an empty target in Object.assign.