How to Merge Two Objects with the Same Key in JavaScript

When you work with JSON data or state management apps, you’ll probably have to merge objects with the same key in JavaScript. Doing so requires you to combine properties from two or more objects into a single object.

Overview of Object Merging

When merging two objects, if they share the same key, the value from the last object will typically overwrite the initial one. You can use JavaScript's Object.assign() method or the spread operator for this.

Using Object.assign

Object.assign() is a method that copies the values of all enumerable own properties from one or more source objects to a target object.

const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = Object.assign({}, object1, object2);

Spread Operator

The spread operator (...) allows an iterable such as an array or string to be expanded in places where zero or more arguments or elements are expected.

const object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = { ...object1, ...object2 };

Custom Merge Functions

For more complex merging scenarios, you can use custom merge functions. This allows for handling deep merges, array concatenation, or special conflict resolution logic.

function customMerge(obj1, obj2) { let merged = { ...obj1 }; for (let key in obj2) { if (obj2.hasOwnProperty(key)) { merged[key] = obj1[key] && obj1[key].toString() === '[object Object]' ? customMerge(obj1[key], obj2[key]) : obj2[key]; } } return merged; }

Handling Arrays and Nested Objects

When merging objects containing arrays or nested objects, consider if you need to merge the nested elements or overwrite them.

const object1 = { a: [1, 2], b: { c: 3 } }; const object2 = { a: [3, 4], b: { d: 4 } }; const mergedObject = { a: [...object1.a, ...object2.a], b: customMerge(object1.b, object2.b), };

Libraries for Advanced Merging

For deep merging or handling complex data structures, libraries like Lodash offer functions like _.merge() that can simplify the process.

// Using Lodash merge function const _ = require('lodash'); const mergedObject = _.merge({}, object1, object2);

Invite only

We're building the next generation of data visualization.