How can I merge properties of two JavaScript objects?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
To merge properties of two JavaScript objects, there are multiple methods you can use depending on your requirements and the environment you are working in. Below are the most common and modern approaches:
1. Using the Spread Operator (...)
The spread operator (ES6 feature) allows you to merge properties from multiple objects into a new object.
Example:
Behavior:
- If the same property exists in both objects, the property from the second object (
obj2) will overwrite the one from the first (obj1). - This creates a new object, leaving the original objects unchanged.
2. Using Object.assign()
The Object.assign() method merges properties into a target object.
Example:
Behavior:
- The first parameter (
{}) is the target object. It ensures the original objects (obj1andobj2) are not modified. - Like the spread operator, properties in
obj2overwrite those inobj1if they have the same key.
3. Merging Deeply Nested Objects
If you need to deeply merge objects (including nested properties), the spread operator and Object.assign() won't work as expected because they perform a shallow merge.
For deep merging, you can use:
lodash.merge(third-party library).- Custom deep merge logic.
Using lodash.merge:
First, install lodash:
Example:
Custom Deep Merge Function:
4. Using Modern Libraries for Complex Merges
For robust object merging in complex scenarios, libraries like lodash or deepmerge provide ready-to-use solutions:
- Lodash:
_.merge() - Deepmerge: Lightweight deep merging library. Install with:
Comparison of Methods
| Method | Type | Deep Merge Support | Notes |
Spread Operator (...) | Built-in (ES6) | ❌ No | Easy for shallow merging. |
Object.assign() | Built-in | ❌ No | Similar to spread operator. |
lodash.merge | Third-party library | ✅ Yes | Great for deep merges. |
| Custom Function | Manual implementation | ✅ Yes | Customizable for specific needs. |
deepmerge | Third-party library | ✅ Yes | Lightweight and simple for deep merges. |
Recommendation
- Use the spread operator (
...) for simple, shallow merges. - Use
lodash.mergeordeepmergefor deep merges with nested properties. - Avoid modifying the original objects unless necessary.
By choosing the right method based on your use case, you can efficiently merge objects in JavaScript. 🚀

