how to merge objects in javascript
There are various ways to combine two objects in JavaScript. Whether you want to conduct a shallow or deep merge will determine which technique you use.
1. Shallow Merge (Overwrite Properties)
- Using Object.assign():
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = Object.assign({}, obj1, obj2);
// Result: { a: 1, b: 3, c: 4 }
- Using the Spread Operator (...):
const merged = {...obj1,...obj2 };
// Result: { a: 1, b: 3, c: 4 }
Note: Both methods are shallow merges—nested objects/arrays are all by reference (not cloned). If there are duplicate keys, subsequent properties will overwrite prior ones.
2. Deep Merge (Recursively Combine Nested Properties)
- Using Lodash:
const merged = _.merge({}, obj1, obj2);
- Custom Deep Merge Function (Simplified Example):
function deepMerge(target, source) {
for (const key in source) {
if (source[key] instanceof Object && target[key]) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
const merged = deepMerge({}, { a: { x: 1 } }, { a: { y: 2 } });
// Result: { a: { x: 1, y: 2 } }
Other Considerations
- Shallow Merge: For simple scenarios, employ Object.assign() or the spread operator.
- Deep Merge: For greater resilience, use a tool such as Lodash (e.g. _.merge()), which is able to contend with sophisticated structures, including arrays and null values
- Overwriting Behavior: In situations involving conflict over keys, later objects always win.