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

Or you can use a recursive approach. Here’s an example function that merges two objects, including their nested properties:

function mergeObjects(obj1, obj2) {
  var merged = { ...obj1 }; // Create a shallow copy of obj1

  for (var key in obj2) {
    if (obj2.hasOwnProperty(key)) {
      if (typeof obj2[key] === 'object' && obj2[key] !== null && !Array.isArray(obj2[key])) {
        // If the property is an object (but not an array or null), merge recursively
        if (obj1.hasOwnProperty(key) && typeof obj1[key] === 'object' && obj1[key] !== null && !Array.isArray(obj1[key])) {
          merged[key] = mergeObjects(obj1[key], obj2[key]);
        } else {
          merged[key] = { ...obj2[key] }; // Create a shallow copy of obj2's nested object
        }
      } else {
        // Non-object properties are directly assigned
        merged[key] = obj2[key];
      }
    }
  }

  return merged;
}
var obj1 = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3
    }
  }
};

var obj2 = {
  b: {
    d: {
      f: 4
    }
  },
  g: 5
};

var mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading