I know this is a bit of an old issue but the easiest solution in ES2015/ES6 I could come up with was actually quite simple, using Object.assign(),

Hopefully this helps:

/**
 * Simple object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

/**
 * Deep merge two objects.
 * @param target
 * @param ...sources
 */
export function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

Example usage:

mergeDeep(this, { a: { b: { c: 123 } } });
// or
const merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});  
console.dir(merged); // { a: 1, b: { c: { d: [Object] } } }

You'll find an immutable version of this in the answer below.

Note that this will lead to infinite recursion on circular references. There's some great answers on here on how to detect circular references if you think you'd face this issue.

Answer from Salakar on Stack Overflow
Top answer
1 of 15
316

I know this is a bit of an old issue but the easiest solution in ES2015/ES6 I could come up with was actually quite simple, using Object.assign(),

Hopefully this helps:

/**
 * Simple object check.
 * @param item
 * @returns {boolean}
 */
export function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

/**
 * Deep merge two objects.
 * @param target
 * @param ...sources
 */
export function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

Example usage:

mergeDeep(this, { a: { b: { c: 123 } } });
// or
const merged = mergeDeep({a: 1}, { b : { c: { d: { e: 12345}}}});  
console.dir(merged); // { a: 1, b: { c: { d: [Object] } } }

You'll find an immutable version of this in the answer below.

Note that this will lead to infinite recursion on circular references. There's some great answers on here on how to detect circular references if you think you'd face this issue.

2 of 15
254

You can use Lodash merge:

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

console.log(_.merge(object, other));
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

🌐
GitHub
gist.github.com › ahtcx › 0cd94e62691f539160b32ecda18af3d6
Deep-Merge JavaScript objects with ES6 · GitHub
let target = {...existing,...newdata}; This code will be more than enough to merge the data by using javascript. As explain by @ahtcx , this gist is old. But its purpose is to merge objects deeply.
Discussions

How can I perform a deep merge rather than a shallow merge?
Standard JavaScript methods like Object.assign and the object spread operator create shallow merges. Consider this issue: // Flat structure const obj1 = { key1: 5 }; const obj2 = { key2: 7 }; const mergedObj = { ...obj1, ...obj2 }; // { key1: 5, key2: 7 } This behaves as expected. More on community.latenode.com
🌐 community.latenode.com
0
0
October 12, 2024
Help with typing a deep merge function.
Hey all, I'm wondering if there are any smart people out there looking a little bit of a challenge. On the surface this didn't seem like it would be… More on reddit.com
🌐 r/typescript
10
7
November 9, 2020
Is there a benefit to using lodash.merge (or other utilities of the same feature) versus merging via object destructuring?
Yes, absolutely. Lodash merge recursively merges properties at every level. If you merged two objects with destructuring (or lodash.assign or Object.assign which are equivalent), it drops anything that is not top-level from the first object. See: https://lodash.com/docs#merge More on reddit.com
🌐 r/node
13
4
November 14, 2022
Deep merging objects in mongodb update pipeline

I have coded this function in php to do that.

private function recursiveMergeArray($tomerge, $newdata) { foreach ($newdata as $key => $newValue) { if ( isset($tomerge[$key]) && is_array($tomerge[$key]) && is_array($newValue) ) $newValue = self::recursiveMergeArray($tomerge[$key], $newValue);

    $tomerge[$key] = $newValue;
  }
  return $tomerge;
}

It work perfectly for my case. If it can help.

More on reddit.com
🌐 r/mongodb
4
3
January 27, 2022
🌐
Medium
medium.com › @abbas.ashraf19 › 8-best-methods-for-merging-nested-objects-in-javascript-ff3c813016d9
8 Best Methods for Merging Nested Objects in JavaScript | by Abbas Ashraf Mughal | Medium
February 15, 2024 - While it performs a shallow merge, it's a quick and clean solution for simple cases. ... For a deep merge, a recursive function can be employed to traverse and merge nested objects at all levels.
🌐
JavaScript in Plain English
javascript.plainenglish.io › merging-javascript-objects-a-deep-dive-bbb00dc51cba
Merging JavaScript Objects: A Deep Dive | by Yogesh Datir | JavaScript in Plain English
December 9, 2024 - Merging JavaScript Objects: A Deep Dive Understanding and Implementing Deep Object Merging Merging JavaScript objects is a fundamental technique that involves combining properties from two or more …
🌐
npm
npmjs.com › package › deepmerge
deepmerge - npm
March 16, 2023 - A library for deep (recursive) merging of Javascript objects. Latest version: 4.3.1, last published: 3 years ago. Start using deepmerge in your project by running `npm i deepmerge`. There are 12608 other projects in the npm registry using deepmerge.
      » npm install deepmerge
    
Published   Mar 16, 2023
Version   4.3.1
🌐
Go Make Things
gomakethings.com › how-to-deep-merge-arrays-and-objects-with-javascript
How to deep merge arrays and objects with JavaScript | Go Make Things
April 27, 2023 - ['Dancing teacups', 'Disappear', 'Talks to animals', 'Navigate'] Unfortunately, there’s currently no native JavaScript method for doing a deep merge, so we’ll need to create a helper function.
🌐
npm
npmjs.com › package › object-deep-merge
object-deep-merge - npm
October 20, 2025 - type Data = { name: string; description: string; }; const base: Data = { name: "object-deep-merge", description: "merge objects" }; const overrides: Partial<Data> = { description: "merge objects, deeply" }; const merged = merge(base, overrides); // Type is inferred so the signature becomes: // function merge<Partial<Data>, Partial<Data>>(source: Partial<Data>, target: Partial<Data>, ...targets: Partial<Data>[]): Partial<Data> // TData = Partial<Data> // TResult = Data console.log({ merged });
      » npm install object-deep-merge
    
Published   Oct 20, 2025
Version   2.0.0
Author   Forcir Engineering
Find elsewhere
🌐
CoreUI
coreui.io › blog › how-to-merge-objects-in-javascript
How to Merge Objects in JavaScript · CoreUI
February 27, 2024 - When your project requires deep merging, the Lodash library offers a powerful solution with its merge() function. This method goes beyond the surface, recursively merging objects at all levels, making it ideal for complex data structures.
🌐
GitHub
github.com › TehShrike › deepmerge
GitHub - TehShrike/deepmerge: A library for deep (recursive) merging of Javascript objects · GitHub
A library for deep (recursive) merging of Javascript objects - TehShrike/deepmerge
Starred by 2.8K users
Forked by 216 users
Languages   JavaScript 95.8% | TypeScript 4.2%
🌐
Latenode
community.latenode.com › other questions › javascript
How can I perform a deep merge rather than a shallow merge? - JavaScript - Latenode Official Community
October 12, 2024 - Standard JavaScript methods like Object.assign and the object spread operator create shallow merges. Consider this issue: // Flat structure const obj1 = { key1: 5 }; const obj2 = { key2: 7 }; const mergedObj = { ...obj1, ...obj2 }; // { key1: 5, key2: 7 } This behaves as expected.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › assign
Object.assign() - JavaScript - MDN Web Docs
const obj1 = { a: 0, b: { c: 0 } }; const obj2 = Object.assign({}, obj1); console.log(obj2); // { a: 0, b: { c: 0 } } obj1.a = 1; console.log(obj1); // { a: 1, b: { c: 0 } } console.log(obj2); // { a: 0, b: { c: 0 } } obj2.a = 2; console.log(obj1); // { a: 1, b: { c: 0 } } console.log(obj2); // { a: 2, b: { c: 0 } } obj2.b.c = 3; console.log(obj1); // { a: 1, b: { c: 3 } } console.log(obj2); // { a: 2, b: { c: 3 } } // Deep Clone const obj3 = { a: 0, b: { c: 0 } }; const obj4 = structuredClone(obj3); obj3.a = 4; obj3.b.c = 4; console.log(obj4); // { a: 0, b: { c: 0 } }
🌐
egghead.io
egghead.io › lessons › javascript-deep-merge-objects-in-javascript-with-spread-lodash-and-deepmerge
Deep Merge Objects in JavaScript with Spread, Lodash, and Deepmerge | egghead.io
In this lesson, we'll look at three different ways to deeply merge objects, depending on what you want to accomplish: using the spread operator, using lodash's merge function, or using the deepmerge npm library.
Published   January 17, 2019
🌐
TutorialsPoint
tutorialspoint.com › how-to-deep-merge-two-objects-in-javascript
How to Deep Merge Two Objects in JavaScript?
January 6, 2025 - A custom function provides complete control over how the merge operates. function deepMerge(obj1, obj2) { const result = { ...obj1 }; // Start with a shallow copy of obj1 for (const key in obj2) { if (obj2[key] && typeof obj2[key] === "object" && !Array.isArray(obj2[key])) { result[key] = deepMerge(result[key] || {}, obj2[key]); } else { result[key] = obj2[key]; } } return result; } // Example usage const obj1 = { name: "Pankaj", details: { age: 21, skills: ["JavaScript"] } }; const obj2 = { details: { age: 22, location: "India" }, hobbies: ["Coding"] }; const merged = deepMerge(obj1, obj2); console.log(merged);
🌐
LabEx
labex.io › tutorials › javascript-deep-merge-objects-28266
Mastering Deep Object Merging in JavaScript | LabEx
To deeply merge two objects in JavaScript, you can use the deepMerge function. This function takes two objects and a function as arguments.
🌐
Medium
medium.com › @srajas02 › merge-two-objects-deeply-nested-in-javascript-8e8515b4f8d3
Merge two objects deeply nested in Javascript | by RAJA S | Medium
November 18, 2022 - In this blog, you will learn how two objects can be merged deeply nested objects. Javascript is offering Object.assign() and Spread Operator to merge the objects.
🌐
Better Programming
betterprogramming.pub › how-to-merge-deeply-nested-objects-in-javascript-27e12107480e
How to Merge Deeply Nested Objects in JavaScript | by Yogesh Chavan | Better Programming
July 15, 2022 - How to Merge Deeply Nested Objects in JavaScript The way to correctly merge nested objects There are many scenarios where we need to merge two objects that may be deeply nested. In this article, we …
🌐
Kranthi Lakum
lakum.in › blog › shallow-merge-vs-deep-merge-in-javascript
Shallow merge vs. Deep merge in JavaScript | Kranthi Lakum
For each key, the function checks if the value of the key in the target object is an object and also the value of the key in the source object is an object, if so the function calls itself recursively to merge the nested objects. If the value of the key in the target object is not an object or the value of the key in the source object is not an object, then it assigns the value of the key in the source object to the key in the target object. In this example, the deep merge correctly combines the properties of obj1 and obj2, including the nested object b and the array c and also adds the new key d from obj2 to the final object.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › merge objects
JavaScript - Deep merge objects
March 20, 2024 - const deepMerge = (a, b, fn) => [...new Set([...Object.keys(a), ...Object.keys(b)])].reduce( (acc, key) => ({ ...acc, [key]: fn(key, a[key], b[key]) }), {} ); const obj1 = { a: true, b: [1, 2, 3], c: { d: 4, e: 5 }, f: 'foo', }; const obj2 = { a: false, b: [4, 5, 6], c: { d: 6, g: 7 }, f: 'bar', }; const concatFn = (key, a, b) => { if (Array.isArray(a) && Array.isArray(b)) return a.concat(b); if (typeof a === 'object' && typeof b === 'object') return deepMerge(a, b, concatFn); if (typeof a === 'string' && typeof b === 'string') return [a, b].join(' '); return b ?? a; }; deepMerge(obj1, obj2, concatFn); // { // a: false, // b: [ 1, 2, 3, 4, 5, 6 ] // c: { d: 6, e: 5, g: 7 }, // f: 'foo bar' // } ... Master array manipulation in JavaScript with this ES6 article collection. ... Learn how to merge two arrays of objects, while combining objects based on a specified key.
🌐
David Walsh
davidwalsh.name › javascript-deep-merge
JavaScript Deep Merge
March 7, 2017 - When you use the deepmerge utility, you can recursively merge any number of objects (including arrays) into one final object.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-deep-merge-two-objects-in-javascript
How to Deep Merge Two Objects in JavaScript
July 26, 2024 - Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.