Skip to content

Merge nested objects JavaScript | Example code

  • by

Use a recursive approach to merge nested objects in JavaScript. You have to use reduce()method for this approach.

Merge nested objects JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    function merge(a, b) {
      return Object.entries(b).reduce((o, [k, v]) => {
        o[k] = v && typeof v === 'object'
        ? merge(o[k] = o[k] || (Array.isArray(v) ? [] : {}), v)
        : v;
        return o;
      }, a);
    }

    let target = { "key1": { "id": 1 }, "key2": { "id": 1, "key": "value" } }
    let source = { "key2": { "id": 2 } }

    console.log([{}, target, source].reduce(merge));
  </script>

</body>
</html> 

Output:

Merge nested objects JavaScript

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *