How to Merge Two Objects in JavaScript
In JavaScript, it is possible to merge the properties of two or more objects and make a new object by using the spread operator. The spread operator was standardised in ECMAScript 2018 and is represented by ...
(three dots) preceding an object. Let's have a look at this in action.
Using the Spread Operator
To use the spread operator we will create a new object containing a comma-separated list of objects to merge, each preceded by ...
(three dots) .
var fruit_1 = {'apples': 2, 'strawberries': 2, 'oranges': 2}
var fruit_2 = {'apples': 3, 'bannas': 2, 'lemmons': 2, 'apricots': 2}
result = {...fruit_1, ...fruit_2}
console.log(result)
{'apples': 3, 'strawberries': 2, 'oranges': 2, 'bannas': 2, 'lemmons': 2, 'apricots': 2}
note - if an object contains the same property name as a previous one in the argument list it will replace the previous one. In the example above we can see the value of apples in fruit_2
was used instead of the value of apples in fruit_1
.
Merge objects using Object.assign() method
It is also possible to merge objects using the Object.assign()
method. The first argument is the target object and subsequent arguments are the objects to add. If a property of the same name already exists on the target, its value will be replaced by the merging value.
var target = {'apples': 2, 'strawberries': 2, 'oranges': 2}
var fruit_2 = {'apples': 3, 'bannas': 2, 'lemmons': 2, 'apricots': 2}
result = Object.assign(target, fruit_2)
console.log(result)
{'apples': 3, 'strawberries': 2, 'oranges': 2, 'bannas': 2, 'lemmons': 2, 'apricots': 2}
The property apples
exists on both objects so, the value from fruit_2
was used.
Deep Merging
To perform recursive deep merges the best option is to install Lodash.merge through npm. This will be much easier than creating a custom function to perform deep merges.
Conclusion
You now know how to merge objects in JavaScript and what behaviour to watch out for. When performing a shallow merge of a lot of objects it may make your code cleaner to use the Object.assign()
method instead of the spread operator.