To merge properties of two JavaScript objects, you can use one of the following methods depending on your use case:
1. Using the Spread Operator (...
) (ES6+)
Creates a new object by merging properties from multiple objects.
Properties with the same key are overwritten by the last object.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged);
// Output: { a: 1, b: 3, c: 4 } (obj2's "b" overrides obj1's "b")
2. Using Object.assign()
(ES5+)
Merges objects into a target object (modifies the target object).
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = Object.assign({}, obj1, obj2); // Merge into a new object
// const merged = Object.assign(obj1, obj2); // Modifies obj1 directly
console.log(merged);
// Output: { a: 1, b: 3, c: 4 }
3. Deep Merge (Nested Objects)
Both methods above perform a shallow merge. For deep merging (nested objects), use a library like Lodash or write a custom function:
Using Lodash:
const _ = require('lodash');
const obj1 = { a: 1, b: { x: 2 } };
const obj2 = { b: { y: 3 }, c: 4 };
const merged = _.merge({}, obj1, obj2);
console.log(merged);
// Output: { a: 1, b: { x: 2, y: 3 }, c: 4 }
Custom Deep Merge (Simplified):
function deepMerge(target, source) {
for (const key in source) {
if (typeof source[key] === 'object' && !Array.isArray(source[key])) {
target[key] = deepMerge(target[key] || {}, source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
const merged = deepMerge({}, obj1, obj2);
Key Notes
- Shallow Merge: Only top-level properties are merged. Nested objects are replaced, not merged.
- Overwriting: Conflicting keys are resolved by the last object in the sequence.
- Immutability: Use
...
orObject.assign({}, ...)
to avoid modifying the original objects.
Summary
Method | Use Case | Example |
---|---|---|
Spread Operator (... ) | Modern syntax, simple shallow merge | { ...obj1, ...obj2 } |
Object.assign() | ES5-compatible shallow merge | Object.assign({}, obj1, obj2) |
Deep Merge | Merging nested objects | Use Lodash or custom logic |
Choose the method that fits your needs and environment!