NeuroAgent

Complete Guide to Merging JavaScript Objects

Learn how to merge JavaScript objects using Object.assign(), spread operator, and custom methods. Handle conflicts and optimize performance with our complete guide.

Question

How can I merge properties of two JavaScript objects?

I need to be able to merge two simple JavaScript objects at runtime. For example:

javascript
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

Is there a built-in way to do this? I don’t need recursion, and I don’t need to merge functions, just properties on flat objects.

NeuroAgent

The most straightforward way to merge properties of two JavaScript objects is using the built-in Object.assign() method or the modern spread operator (...). For your specific example where you want to add a merge() method to objects, you can either use these methods directly or create a custom merge function.

Contents

Using Object.assign()

The Object.assign() method is the most common built-in way to merge objects in JavaScript. It copies all enumerable own properties from one or more source objects to a target object and returns the modified target object.

javascript
var obj1 = { food: 'pizza', car: 'ford' };
var obj2 = { animal: 'dog' };

// Merge obj2 into obj1
Object.assign(obj1, obj2);

console.log(obj1); // { food: 'pizza', car: 'ford', animal: 'dog' }

The syntax is: Object.assign(target, ...sources)

You can also merge multiple objects at once:

javascript
var obj1 = { a: 1 };
var obj2 = { b: 2 };
var obj3 = { c: 3 };

Object.assign(obj1, obj2, obj3);
// obj1 now has properties: a: 1, b: 2, c: 3

According to the Mozilla Developer Network, “The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.”

Using the Spread Operator

The spread operator (...) introduced in ES6 provides a more concise way to merge objects:

javascript
var obj1 = { food: 'pizza', car: 'ford' };
var obj2 = { animal: 'dog' };

// Create a new merged object
var mergedObj = { ...obj1, ...obj2 };

console.log(mergedObj); // { food: 'pizza', car: 'ford', animal: 'dog' }

This approach creates a completely new object without modifying the original objects. As noted in the research from SitePoint, “The merged object will contain all the properties and methods from the original objects, regardless of their data types.”

Adding a Custom merge() Method

Since you want to be able to call obj1.merge(obj2), you can extend the Object prototype with a custom merge method. Here’s how to do it:

javascript
// Add merge method to Object prototype
Object.prototype.merge = function(source) {
    return Object.assign(this, source);
};

// Now you can use it as you wanted
var obj1 = { food: 'pizza', car: 'ford' };
var obj2 = { animal: 'dog' };

obj1.merge(obj2);

console.log(obj1); // { food: 'pizza', car: 'ford', animal: 'dog' }

Alternatively, if you prefer not to modify the Object prototype, you can create a utility function:

javascript
function merge(target, source) {
    return Object.assign(target, source);
}

// Usage
var obj1 = { food: 'pizza', car: 'ford' };
var obj2 = { animal: 'dog' };

merge(obj1, obj2);

console.log(obj1); // { food: 'pizza', car: 'ford', animal: 'dog' }

Key Differences and When to Use Each Method

Here’s a comparison of the main methods:

Method Syntax Modifies Target Returns New Object Best For
Object.assign() Object.assign(target, source) Yes No In-place merging, performance-critical code
Spread Operator {...obj1, ...obj2} No Yes Immutable operations, modern ES6+ code
Custom merge obj1.merge(obj2) Yes No Convenience, object-oriented approach

As mentioned in the research from Stack Overflow, “Object.assign(obj1, obj2); may be the preferable way as let merged = {…obj1, …obj2}; creates a new object and copies the properties of obj1 and obj2 into it which may be very expensive for large objects.”

Handling Property Conflicts

When both objects have properties with the same name, the later object’s properties overwrite the earlier ones:

javascript
var obj1 = { name: 'John', age: 25 };
var obj2 = { name: 'Jane', city: 'New York' };

// Using Object.assign
Object.assign(obj1, obj2);
console.log(obj1.name); // 'Jane' (obj2's value overwrites obj1's)

// Using spread operator
var merged = { ...obj1, ...obj2 };
console.log(merged.name); // 'Jane'

The GeeksforGeeks documentation confirms that “if there are multiple keys then merged values will be overwritten from left to right order of parameters.”

Performance Considerations

For performance-critical applications with large objects, Object.assign() is generally more efficient than the spread operator because it doesn’t create an intermediate object. However, for most use cases with small to medium-sized objects, the difference is negligible.

The research from JavaScript Tutorial notes that “The Object.assign() method allows you to copy all enumerable own properties from one or more source objects to a target object, and return the target object.”


Conclusion

  1. Use Object.assign() for the most straightforward built-in method to merge objects in place
  2. Use the spread operator when you need to create a new merged object without modifying the originals
  3. Create a custom merge method if you prefer the obj1.merge(obj2) syntax for convenience
  4. Be aware of property conflicts - later objects overwrite earlier ones with the same property names
  5. Consider performance - Object.assign() is generally more efficient for large objects

For your specific use case with flat objects, any of these methods will work well. The Object.assign() approach is the most traditional and widely supported, while the spread operator offers more modern syntax and immutability.

Sources

  1. Object.assign() - JavaScript | MDN
  2. How to Merge Objects in JavaScript — SitePoint
  3. How can I merge properties of two JavaScript objects? - Stack Overflow
  4. JavaScript Object.assign() - Programiz
  5. How to Merge Objects in JavaScript - JavaScript Tutorial
  6. JavaScript Object.assign() Method - GeeksforGeeks
  7. ES6 Merge Objects - GeeksforGeeks