Anjan Dutta

Javascript merge objects

Javascript merge objects

There are two ways we can merge javascript objects.

First is using Object.assign() method and second is by using a spread operator.

let person = {name: 'John', age: 30, address: '18/1, Dover lane' };
var details = {phone: 1234567890};
let ph = {height: '196cm'}
console.log(Object.assign({},person, details, ph));

This method will merge all three objects in one and will return the merged object. We can use any of the objects in the first place. Then all the other objects will be merged to the first object and that will be returned in the end.

Another way is to use the spread (...) operator.

Using spread operator the code would look like below.

let merged = {...person, ...details, ...ph};