DEV Community

Discussion on: How to merge object in javascript

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