This post will discuss how to merge the properties of two or more objects in JavaScript.

1. Using Spread Operator

A simple solution is to use the Spread operator to expand the properties of the specified objects into literal objects (ES2018). Here’s a working example:

Download  Run Code

 
The solution returns a new array object and can be easily extended to merge any number of objects.

Note that the properties of the subsequent objects will completely overwrite the properties of former objects with the same key. This is true for the following solutions as well.

2. Using Object.assign() function

The Object.assign() method copies all properties from one or more source objects to a target object and returns the target object. You can use this as:

Download  Run Code

 
The Object.assign() method can accept an arbitrary number of objects. To avoid modifying the original objects, pass an empty object as the target:

Download  Run Code

3. Using jQuery

With jQuery, you can use the $.extend() method, which copies all properties from the specified object to the target object and return the target object.

 
The $.extend() method can merge an arbitrary number of objects. If the first argument to $.extend is true, the method performs a deep copy. To get a new object without modifying the original object, pass an empty object as the target:

4. Using Underscore/Lodash Library

If you’re already using the Underscore or Lodash library, another good alternative is to use the _.extend method. It copies all the source object’s properties to the destination object and returns the destination object.

 
Like Object.assign() and $.extend(), it can accept any number of arguments. To get a new object without modifying the original objects, pass an empty object as the target.

 
With Lodash, you can also use the _.merge() method that works similarly:

That’s all about merging properties of two or more objects in JavaScript.