Merge multiple objects in JavaScript

Programming JavaScript

You may have a need to merge two objects together and create a better informative object to work with. You can use the spread operator ... (yes, that are three dots).

Consider the two objects emp and job:

let emp = {
'id': 'E_01',
'name': 'Jack',
'age': 32,
'addr': 'India'
};

let job = {
'title': 'Software Dev',
'location': 'Paris'
};

You can merge them via the ... spread operator into a single object:

 // spread operator
let merged = {...emp, ...job};
console.log('Spread merged', merged);

There is another way to perform this merge via Object.assign()

console.log('Object assign', Object.assign({}, emp, job));

The output will be:


Note, both the spread operator and the Object.assign perform a shallow merge. In a shallow merge, the properties of the first object are overwritten with the same property values as the second object.

For deep merge, please use something like for example _merge of lodash.