Ask Your Question
4

How to perform a deep merge of two JSON objects using ES6?

asked 2023-02-06 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-02-14 12:00:00 +0000

lakamha gravatar image

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' } }
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-06 11:00:00 +0000

Seen: 17 times

Last updated: Feb 14 '22