Need to merge two JavaScript objects without losing nested properties? The spread operator and Object.assign() only copy the top level, so a nested object in the second object replaces the whole nested object in the first. This guide shows the best ways to merge nested objects in JavaScript, when to use each one, how arrays behave, and how to merge user input safely.
Quick answer: Use spread ({ ...a, ...b }) when your objects are one level deep. For nested objects, use a small recursive deep-merge function or Lodash's _.merge({}, a, b).
- Flat objects:
{ ...defaults, ...overrides }. - Nested objects with no dependency: the
mergeDeep()function in Method 3. - Arrays merged too, or many edge cases:
_.merge({}, a, b). - Need a result that shares nothing with the inputs: wrap it in
structuredClone(). - Merging request bodies or other user input: skip
__proto__,constructorandprototype, and validate the shape first.
In this guide
- Table of Contents
- Which Merge Method Should You Use?
- What a Nested Object Is (and Why Merging Breaks)
- Method 1: Spread Operator (Shallow Merge)
- Method 2: Object.assign() (Shallow, Writes Into the Target)
- Method 3: A Recursive Deep-Merge Function
- Method 4: Lodash _.merge()
- How Each Method Handles Arrays
- Get an Independent Copy with structuredClone()
- Merge User Input Safely (Prototype Pollution)
- Practical Examples
- Common Mistakes and Fixes
- Frequently Asked Questions
- Next Steps
- References
Table of Contents
- Which Merge Method Should You Use?
- What a Nested Object Is (and Why Merging Breaks)
- Method 1: Spread Operator
- Method 2:
Object.assign() - Method 3: A Recursive Deep-Merge Function
- Method 4: Lodash
_.merge() - How Each Method Handles Arrays
- Get an Independent Copy with
structuredClone() - Merge User Input Safely (Prototype Pollution)
- Practical Examples
- Common Mistakes and Fixes
- Frequently Asked Questions
Which Merge Method Should You Use?
A shallow merge copies only the top-level keys. A deep merge walks into nested objects and combines their keys too. Pick the method by how deep your data goes and whether the inputs must stay untouched.
| Method | Depth | Arrays | Changes the inputs? | Use it when |
|---|---|---|---|---|
{ ...a, ...b } | Shallow | Replaced | No | Objects are flat, or you only override top-level keys |
Object.assign(target, a, b) | Shallow | Replaced | Yes, it writes into target | You want to update an existing object in place |
mergeDeep(a, b) (Method 3) | Deep | Replaced | No, but untouched nested objects are shared | Config or settings objects, no extra dependency |
_.merge({}, a, b) | Deep | Merged by index | Only the first argument | Complex data, or you already use Lodash |
structuredClone(x) | Deep copy, not a merge | Copied | No | You need a result that shares no objects with the inputs |
Where to run the examples: paste any snippet into your browser's developer console, or save it as merge.js and run node merge.js in a terminal (Node.js 17 or later, because structuredClone() arrived in Node 17). The // Output: comment under each console.log() shows what you should see. The later snippets reuse the mergeDeep() function from Method 3, so paste that first.
What a Nested Object Is (and Why Merging Breaks)
A nested object is an object stored as the value of another object's property.
const obj1 = {
name: 'John',
address: {
city: 'New York',
zip: 10001
}
};Here address is a nested object inside obj1. If you merge in { address: { zip: 10002 } } with a shallow method, the whole address object is swapped out and city disappears.
Method 1: Spread Operator (Shallow Merge)
The spread operator (...) copies the own enumerable properties of each object into a new object. When two objects share a key, the later one wins. It is the shortest option, and it is shallow.
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { d: 3 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
// Output: { a: 1, b: { c: 2 }, d: 3 }Where spread falls short
When both objects have the same nested key, spread does not combine the nested properties. The second value replaces the first.
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 4 } };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
// Output: { a: 1, b: { d: 4 } }The b object from obj1 is gone, so c: 2 is lost. You can fix one level by hand with { ...obj1, ...obj2, b: { ...obj1.b, ...obj2.b } }, but that gets unreadable past two levels.
Method 2: Object.assign() (Shallow, Writes Into the Target)
Object.assign(target, ...sources) copies each source's top-level properties into target and returns it. It changes target, so pass an empty object first when you want a new object.
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { d: 3 };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj);
// Output: { a: 1, b: { c: 2 }, d: 3 }Same limit as spread
Object.assign() is also shallow, so nested objects are replaced rather than merged.
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 4 } };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj);
// Output: { a: 1, b: { d: 4 } }The nested b object from obj1 is replaced by the one from obj2. One small difference from spread: Object.assign() triggers setters on the target, while spread defines plain properties on a new object.
Method 3: A Recursive Deep-Merge Function
To combine nested properties you need a deep merge: a function that calls itself whenever both sides hold an object under the same key. This version has no dependencies and returns a new object instead of changing the inputs.
function isObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function mergeDeep(target, source) {
const output = { ...target };
Object.keys(source).forEach((key) => {
// Skip keys that can be abused for prototype pollution
if (key === '__proto__' || key === 'constructor' || key === 'prototype') return;
if (isObject(source[key]) && isObject(target[key])) {
output[key] = mergeDeep(target[key], source[key]);
} else {
output[key] = source[key];
}
});
return output;
}
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 4 } };
const mergedObj = mergeDeep(obj1, obj2);
console.log(mergedObj);
// Output: { a: 1, b: { c: 2, d: 4 } }How mergeDeep works
- It starts with a shallow copy of
target, so the original is not changed. - For each key in
source,isObject()checks whether both sides hold a plain-looking object (notnull, not an array). - If they do, it merges those two objects by calling itself. Otherwise the
sourcevalue wins. Arrays are replaced, not merged. - It skips
__proto__,constructorandprototype. The prototype pollution section below explains why.
Limits to know before you rely on it
- Shared references: nested objects that only one side has are copied by reference. Changing them in the result also changes the input. Use
structuredClone()if that matters. undefinedoverwrites:{ theme: undefined }insourcereplaces a real value, the same as spread does.- Dates, Maps and class instances:
isObject()returnstruefor them too. If both sides hold aDateunder the same key, the result is an empty plain object. For data like that, use Lodash, which only merges plain objects and arrays.
Method 4: Lodash _.merge()
If your project can take a dependency, Lodash's merge handles more edge cases than a hand-written function. Install it in your project folder with npm install lodash, then run the snippet with Node.
const _ = require('lodash');
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 4 } };
const mergedObj = _.merge({}, obj1, obj2);
console.log(mergedObj);
// Output: { a: 1, b: { c: 2, d: 4 } }_.merge() changes its first argument, which is why an empty object is passed first. Unlike mergeDeep(), it merges arrays index by index, and it skips undefined source values when the destination already has a value.
Why use Lodash instead of your own function
- Handles more types correctly: it merges plain objects and arrays, and assigns other values such as
Dateobjects as they are. - Widely used and tested: fewer surprises with unusual input.
- Customisable:
_.mergeWith()lets you decide how arrays or specific keys are combined.
How Each Method Handles Arrays
Arrays are where deep-merge methods disagree most, so check this before you pick one. Run the snippet below in Node after pasting mergeDeep() and requiring Lodash.
const a = { tags: ['js', 'node'] };
const b = { tags: ['react'] };
console.log(mergeDeep(a, b));
// Output: { tags: ['react'] } (mergeDeep replaces the array)
console.log(_.merge({}, a, b));
// Output: { tags: ['react', 'node'] } (Lodash merges by index)
const concatArrays = (objValue, srcValue) => {
if (Array.isArray(objValue)) return objValue.concat(srcValue);
};
console.log(_.mergeWith({}, a, b, concatArrays));
// Output: { tags: ['js', 'node', 'react'] } (arrays joined)Index-by-index merging often surprises people: 'react' overwrote 'js', and 'node' stayed. For lists such as tags or plugins, replacing (mergeDeep) or joining (_.mergeWith()) is usually what you want. When the customiser returns undefined, Lodash falls back to its normal merge.
Get an Independent Copy with structuredClone()
structuredClone() is built into current browsers and Node.js 17+. It does not merge anything. It makes a deep copy, so the result shares no nested objects with the original. Combine it with a merge when you will change the result later.
const defaults = { theme: 'light', layout: { sidebar: true } };
// Shared reference: changing merged.layout would also change defaults.layout
const merged = mergeDeep(defaults, { theme: 'dark' });
console.log(merged.layout === defaults.layout);
// Output: true
// Independent copy: safe to change
const copy = structuredClone(mergeDeep(defaults, { theme: 'dark' }));
console.log(copy.layout === defaults.layout);
// Output: falsestructuredClone() copies Date, Map, Set and circular references. It throws a DataCloneError if the object contains functions or DOM nodes, and class instances come back as plain objects. See MDN: structuredClone() for the full list.
Merge User Input Safely (Prototype Pollution)
Prototype pollution is an attack where crafted input adds properties to Object.prototype, the object every plain object inherits from. A naive deep merge that writes into its target follows a __proto__ key straight into Object.prototype. After that, every object in your app appears to have the attacker's property, for example isAdmin: true.
The mergeDeep() function above skips the dangerous keys. You can check it with a payload like the one an attacker would send:
// A request body an attacker controls
const body = JSON.parse('{"__proto__": {"isAdmin": true}}');
const settings = mergeDeep({ theme: 'light' }, body);
console.log(settings.isAdmin, {}.isAdmin);
// Output: undefined undefined (the __proto__ key was skipped)Skipping keys is the last line of defence, not the first. Before you merge anything from a request, query string or uploaded file:
- Validate the shape and allow only the keys you expect. A schema library makes this short; see how to validate JSON request bodies with Zod in Express.
- Keep Lodash updated. Older versions had prototype-pollution bugs in functions such as
mergeanddefaultsDeepthat later releases fixed. - For lookups keyed by user input, use a
MaporObject.create(null), which has no prototype to pollute.
Practical Examples
Merge default settings with user settings
A common case: your app ships default settings, and each user saves only the values they changed.
const defaultSettings = {
theme: 'light',
layout: { sidebar: true, footer: true }
};
const userSettings = {
theme: 'dark',
layout: { footer: false }
};
const finalSettings = mergeDeep(defaultSettings, userSettings);
console.log(finalSettings);
// Output: { theme: 'dark', layout: { sidebar: true, footer: false } }The user's footer: false wins, and sidebar: true from the defaults survives. Spread would have dropped sidebar.
Combine two API responses
When two endpoints return different parts of the same record, a deep merge joins them into one object:
const apiResponse1 = {
user: {
name: 'Alice',
contacts: { email: 'alice@example.com' }
}
};
const apiResponse2 = {
user: {
contacts: { phone: '123-456-7890' }
}
};
const combinedData = mergeDeep(apiResponse1, apiResponse2);
console.log(combinedData);
// Output:
// {
// user: {
// name: 'Alice',
// contacts: { email: 'alice@example.com', phone: '123-456-7890' }
// }
// }In React state, the same shallow-versus-deep rule applies. Zustand's set() merges only the top level of your state, and Redux Toolkit uses Immer so you can write nested updates directly. The Zustand vs Redux Toolkit comparison shows both patterns.
Common Mistakes and Fixes
- Nested values disappear after merging. You used spread or
Object.assign()on nested data. Switch tomergeDeep()or_.merge({}, a, b). - Your defaults object changes after a merge. Either
Object.assign()or_.merge()wrote into it (pass{}first), or the result shares nested objects with it (wrap the result instructuredClone()). - A value is wiped out by
undefined. Spread andmergeDeep()copyundefinedvalues. Remove those keys before merging, or use Lodash, which skips them when the destination has a value. - A
Dateturns into{}. The simpleisObject()check treats dates as objects to merge. Use Lodash for data that contains dates, maps or class instances. structuredClone()throwsDataCloneError. The object contains a function, DOM node or similar value. Remove it before cloning, or clone only the data part.
Frequently Asked Questions
What is the difference between a shallow and a deep merge?
A shallow merge copies only top-level keys, so a nested object from the second input replaces the nested object from the first. A deep merge goes into nested objects and combines their keys, so values that only exist in the first input survive.
Does the spread operator make a deep copy?
No. Spread copies only the top level. Nested objects in the new object are the same objects as in the original, so changing copy.address.city also changes the original. Use structuredClone() for a deep copy.
Should I use Lodash merge or write my own function?
Use Lodash if your data includes arrays you want merged, dates, or input you do not fully control, or if Lodash is already installed. A short function like mergeDeep() is fine for config and settings objects made of plain values.
Can I merge more than two objects?
Yes. Spread and Object.assign() accept any number of objects, and later objects win:
const mergedObj = { ...obj1, ...obj2, ...obj3 };For a deep merge of several objects, use _.merge({}, obj1, obj2, obj3) or [obj1, obj2, obj3].reduce(mergeDeep).
Is structuredClone the same as a deep merge?
No. structuredClone() copies one value deeply; it never combines two objects. Use it together with a merge when you need the merged result to share no nested objects with the inputs, for example before you change the result.
Next Steps
Pick the row in the comparison table that matches your data, then paste that method into your project. If you merge request bodies, add schema validation before the merge. Working with dates inside those objects? The JavaScript Temporal API guide covers the newer date types and how to use them today.

