coding
properties
merge
objects
javascript

How can I merge properties of two JavaScript objects?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

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:

javascript
1const obj1 = { a: 1, b: 2 };
2const obj2 = { b: 3, c: 4 };
3
4const merged = { ...obj1, ...obj2 };
5
6console.log(merged);
7// Output: { a: 1, b: 3, c: 4 }

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:

javascript
1const obj1 = { a: 1, b: 2 };
2const obj2 = { b: 3, c: 4 };
3
4const merged = Object.assign({}, obj1, obj2);
5
6console.log(merged);
7// Output: { a: 1, b: 3, c: 4 }

Behavior:

  • The first parameter ({}) is the target object. It ensures the original objects (obj1 and obj2) are not modified.
  • Like the spread operator, properties in obj2 overwrite those in obj1 if 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:

  1. lodash.merge (third-party library).
  2. Custom deep merge logic.

Using lodash.merge:

First, install lodash:

bash
npm install lodash

Example:

javascript
1const _ = require('lodash');
2
3const obj1 = { a: 1, b: { x: 10 } };
4const obj2 = { b: { y: 20 }, c: 3 };
5
6const merged = _.merge({}, obj1, obj2);
7
8console.log(merged);
9// Output: { a: 1, b: { x: 10, y: 20 }, c: 3 }

Custom Deep Merge Function:

javascript
1function deepMerge(target, source) {
2    for (const key in source) {
3        if (source[key] instanceof Object) {
4            target[key] = deepMerge(target[key] || {}, source[key]);
5        } else {
6            target[key] = source[key];
7        }
8    }
9    return target;
10}
11
12const obj1 = { a: 1, b: { x: 10 } };
13const obj2 = { b: { y: 20 }, c: 3 };
14
15const merged = deepMerge({}, obj1);
16deepMerge(merged, obj2);
17
18console.log(merged);
19// Output: { a: 1, b: { x: 10, y: 20 }, c: 3 }

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:
bash
  npm install deepmerge

Comparison of Methods

MethodTypeDeep Merge SupportNotes
Spread Operator (...)Built-in (ES6)❌ NoEasy for shallow merging.
Object.assign()Built-in❌ NoSimilar to spread operator.
lodash.mergeThird-party library✅ YesGreat for deep merges.
Custom FunctionManual implementation✅ YesCustomizable for specific needs.
deepmergeThird-party library✅ YesLightweight and simple for deep merges.

Recommendation

  • Use the spread operator (...) for simple, shallow merges.
  • Use lodash.merge or deepmerge for 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. 🚀


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.