DEV Community

Emmanuel Dalougou
Emmanuel Dalougou

Posted on

How to merge object in javascript

Alt Text

suppose that we have an user object with different values that we will want to merge or updated in the single object:

const user = {
    name: 'John Doe',
    city:'Abidjan',
    job:'web developper'
}

const same_user = {
    name: 'John Doe',
    city:'Abidjan',
    age:24,
    color:'black',
    hobbies:'football'
}

Now, the first question that we ask ourselves is: How to do that ?

We're going to use the spread operator method to do that. The syntax is three dots (...)

const users = {...user, ...same_user}

The spread operator is a new way to spread iterable element or often expand an iterable like array, object.

Now we are going to see the new users object in our NodeJS REPL:

console.log(users)
{ name: 'John Doe', city:'Abidjan', job:'web developper', age:24, color:'black', hobbies:'football' }

Note that this operator was introduced in ES6.

Top comments (2)

Collapse
 
aminnairi profile image
Amin

It is worth noting that this is a shallow merge. Meaning that nested objects won't get merged but erased with the latter ones using the spread operator.

// https://repl.it/repls/CluelessSpectacularOrder
"use strict";

const a = {
    first: true,
    second: {
        third: true
    }
};

const b = {
    first: true,
    second: {
        fourth: true
    }
};

const merged = {...a, ...b};

console.log(JSON.stringify(merged, null, 2));

/*

{
  "first": true,
  "second": {
    "fourth": true (does not include third!!!)
  }
}

*/
Collapse
 
emmanuel_dal profile image
Emmanuel Dalougou

The trouble is that here he will check the value of each key. once the value of a key is different from the previous one then it will remove the old value to keep the new value. whatever the nested objects it will do the same process