Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are multiple ways to perform a deep merge of two JSON objects using ES6. One way is to use the spread operator (...) and recursion. Here is an example function:

function deepMerge(obj1, obj2) {
  let result = {...obj1}; // create a copy of obj1
  Object.keys(obj2).forEach(key => {
    if (result[key] && typeof obj2[key] === 'object') {
      result[key] = deepMerge(result[key], obj2[key]); // recursively merge sub-objects
    } else {
      result[key] = obj2[key]; // otherwise overwrite value
    }
  });
  return result;
}

You can then use this function to merge two JSON objects like this:

const obj1 = {
  foo: 'bar',
  baz: {
    alpha: 'beta'
  }
};

const obj2 = {
  foo: 'baz',
  baz: {
    delta: 'gamma'
  }
};

const merged = deepMerge(obj1, obj2);
console.log(merged);
// Output: { foo: 'baz', baz: { alpha: 'beta', delta: 'gamma' } }