Ask Your Question
4

How can two JSON objects be merged deeply in ES6?

asked 2021-07-21 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-11-12 00:00:00 +0000

ladyg gravatar image

One common way to merge two JSON objects deeply in ES6 is to use the spread operator (...) and recursion.

Here is an example function that takes two JSON objects as input and returns a merged object that includes all the properties of both objects, with nested objects being merged as well:

const mergeObjects = (obj1, obj2) => {
  const merged = {...obj1};

  for (let key in obj2) {
    if (typeof obj2[key] === 'object' && obj2[key] !== null) {
      merged[key] = mergeObjects(merged[key], obj2[key]);
    } else {
      merged[key] = obj2[key];
    }
  }

  return merged;
};

Here, the function starts by creating a copy of obj1 using the spread operator. Then, it iterates over all the keys of obj2. If a key exists in both objects and the value of that key is another object, then the function calls itself recursively to merge those nested objects. Otherwise, it simply copies over the value of the key from obj2 into the merged object.

In this way, a deeply merged object is created that includes all the properties of both original objects.

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: 2021-07-21 11:00:00 +0000

Seen: 15 times

Last updated: Nov 12 '21