Advanced · 9 of 11 · 23 min read
Deep merge and deep copy
Why the spread is not enough, the three ways to copy a whole structure, and a merge function that handles the cases that break naive ones.
- Immutability
- Objects
Both the spread and Object.assign copy one level. Nested objects are shared between the copy
and the original, so a change to one shows up in the other. Everything in this lecture follows from
that.
The problem
const original = {
name: 'app',
config: { theme: 'dark', sizes: { font: 14 } },
};
const shallow = { ...original };
shallow.name = 'copy'; // top level: independent
console.log(original.name); // "app"
shallow.config.theme = 'light'; // nested: the same object
console.log(original.config.theme); // "light" ← the bug
console.log(original.config === shallow.config); // true
Object.assign behaves identically — the two are the same operation with different syntax:
const assigned = Object.assign({}, original);
console.log(assigned.config === original.config); // true
Deep copy, three ways
structuredClone
The right default. Built in, handles cycles, and understands most built-in types:
const original = {
date: new Date('2026-01-01'),
map: new Map([['a', 1]]),
set: new Set([1, 2]),
nested: { deep: { value: 1 } },
array: [1, [2, [3]]],
};
const copy = structuredClone(original);
copy.nested.deep.value = 99;
console.log(original.nested.deep.value); // 1 — truly independent
console.log(copy.date instanceof Date); // true — still a Date
console.log(copy.map.get('a')); // 1 — still a Map
console.log(copy.map === original.map); // false
const cyclic = { name: 'a' };
cyclic.self = cyclic;
console.log(structuredClone(cyclic).self.name); // "a" — cycles are fine
What it cannot clone, and it throws rather than dropping them:
// structuredClone({ fn: () => {} }); // DataCloneError
// structuredClone({ sym: Symbol('x') }); // DataCloneError
// structuredClone(document.body); // DataCloneError (DOM nodes)
It also drops the prototype — a class instance comes back as a plain object:
class User { constructor(n) { this.name = n; } greet() { return this.name; } }
const clone = structuredClone(new User('Ana'));
console.log(clone.name, clone instanceof User, typeof clone.greet); // Ana false undefined
The JSON round trip
Works everywhere, and loses things quietly — which is the real reason to know its failure list:
const original = {
date: new Date('2026-01-01'),
undef: undefined,
fn: () => 1,
nan: NaN,
inf: Infinity,
map: new Map([['a', 1]]),
nested: { ok: true },
};
const copy = JSON.parse(JSON.stringify(original));
console.log(copy);
// {
// date: "2026-01-01T00:00:00.000Z", ← a string now
// nan: null, inf: null, ← null
// map: {}, ← empty
// nested: { ok: true } ← this part worked
// }
// `undef` and `fn` are gone entirely
| Value | structuredClone |
JSON round trip |
|---|---|---|
| nested objects and arrays | copied | copied |
Date |
stays a Date |
becomes a string |
Map / Set |
preserved | {} |
undefined property |
kept | removed |
| function | throws | removed |
NaN / Infinity |
kept | null |
RegExp |
preserved | {} |
BigInt |
kept | throws |
| circular reference | handled | throws |
| class prototype | lost | lost |
| speed | fast | slower |
const cyclic = {};
cyclic.self = cyclic;
// JSON.stringify(cyclic); // TypeError: Converting circular structure to JSON
Recursive, by hand
What the interview asks for, and the honest version with its edge cases handled:
function deepCopy(value, seen = new WeakMap()) {
if (value === null || typeof value !== 'object') return value; // primitives, functions
if (seen.has(value)) return seen.get(value); // a cycle: reuse the copy
if (value instanceof Date) return new Date(value);
if (value instanceof RegExp) return new RegExp(value.source, value.flags);
if (value instanceof Map) {
const out = new Map();
seen.set(value, out);
for (const [k, v] of value) out.set(deepCopy(k, seen), deepCopy(v, seen));
return out;
}
if (value instanceof Set) {
const out = new Set();
seen.set(value, out);
for (const v of value) out.add(deepCopy(v, seen));
return out;
}
const out = Array.isArray(value) ? [] : {};
seen.set(value, out); // before recursing
for (const [key, inner] of Object.entries(value)) {
out[key] = deepCopy(inner, seen);
}
return out;
}
const source = { a: 1, b: { c: [1, 2, { d: 3 }] }, when: new Date(0) };
const copy = deepCopy(source);
copy.b.c[2].d = 99;
console.log(source.b.c[2].d, copy.when instanceof Date); // 3 true
const cyclic = { name: 'x' };
cyclic.self = cyclic;
console.log(deepCopy(cyclic).self.self.name); // "x"
Three details carry the answer: the WeakMap for cycles, registering the copy before recursing
into it, and typeof value !== 'object' catching null only because it is tested first.
Deep merge
Merging is copying plus combining. The naive version is one line and wrong:
const defaults = { api: { url: 'https://a', timeout: 5000 }, debug: false };
const overrides = { api: { timeout: 1000 } };
console.log({ ...defaults, ...overrides });
// { api: { timeout: 1000 }, debug: false } ← `url` is gone
The spread replaced api instead of merging into it. A deep merge recurses where both sides have
an object:
const isPlainObject = (value) =>
value !== null && typeof value === 'object' && !Array.isArray(value) &&
(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
function deepMerge(target, source) {
const out = { ...target };
for (const key of Object.keys(source)) {
const incoming = source[key];
const existing = out[key];
if (isPlainObject(existing) && isPlainObject(incoming)) {
out[key] = deepMerge(existing, incoming); // both objects: recurse
} else {
out[key] = incoming; // otherwise the source wins
}
}
return out;
}
const merged = deepMerge(defaults, overrides);
console.log(merged.api); // { url: 'https://a', timeout: 1000 } — both kept
console.log(defaults.api); // { url: 'https://a', timeout: 5000 } — untouched
The edge cases that are the actual test
Arrays. There is no universally right answer, so the decision has to be deliberate:
const a = { tags: ['x', 'y'] };
const b = { tags: ['z'] };
console.log(deepMerge(a, b).tags); // ["z"] — replace (this version)
console.log([...a.tags, ...b.tags]); // ["x","y","z"] — concatenate
console.log([...new Set([...a.tags, ...b.tags])]); // ["x","y","z"] — union
Replacing is the usual choice for configuration, because concatenating makes a default impossible to remove. Say which one you picked and why.
undefined versus missing. An explicit undefined should usually not overwrite a default:
function deepMergeDefined(target, source) {
const out = { ...target };
for (const key of Object.keys(source)) {
const incoming = source[key];
if (incoming === undefined) continue; // skip it
out[key] = isPlainObject(out[key]) && isPlainObject(incoming)
? deepMergeDefined(out[key], incoming)
: incoming;
}
return out;
}
console.log(deepMergeDefined({ a: 1 }, { a: undefined })); // { a: 1 }
console.log(deepMerge({ a: 1 }, { a: undefined })); // { a: undefined }
null. It is a real value and should overwrite:
console.log(deepMerge({ a: { b: 1 } }, { a: null })); // { a: null } — intentional
Non-plain objects. A Date, a Map or a class instance must be replaced, not walked —
isPlainObject is what prevents a Date from being merged key-by-key into nothing:
console.log(deepMerge({ when: new Date(0) }, { when: new Date(1000) }).when.getTime()); // 1000
console.log(isPlainObject(new Date()), isPlainObject({})); // false true
Prototype pollution. The security edge case, and worth raising unprompted:
const malicious = JSON.parse('{"__proto__": {"isAdmin": true}}');
function safeMerge(target, source) {
const out = { ...target };
for (const key of Object.keys(source)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
out[key] = isPlainObject(out[key]) && isPlainObject(source[key])
? safeMerge(out[key], source[key])
: source[key];
}
return out;
}
const result = safeMerge({}, malicious);
console.log({}.isAdmin); // undefined — nothing leaked onto Object.prototype
A merge that walks attacker-controlled keys and assigns them without this guard is the classic prototype-pollution vulnerability — it has been a real CVE in several popular merge libraries.
Merging many sources, left to right, like Object.assign:
const mergeAll = (...sources) => sources.reduce((acc, source) => deepMerge(acc, source), {});
console.log(mergeAll({ a: { x: 1 } }, { a: { y: 2 } }, { a: { x: 9 } }));
// { a: { x: 9, y: 2 } }
Immutable updates without a merge
For a known path, spreading each level is clearer than a general merge — and this is what reducers do:
const state = {
user: { name: 'Ana', prefs: { theme: 'dark', lang: 'es' } },
items: [1, 2],
};
const next = {
...state,
user: {
...state.user,
prefs: { ...state.user.prefs, theme: 'light' },
},
items: [...state.items, 3],
};
console.log(state.user.prefs.theme, next.user.prefs.theme); // dark light
console.log(state.items.length, next.items.length); // 2 3
console.log(state.user.prefs === next.user.prefs); // false — this path was copied
console.log(state.items === next.items); // false
Note what is not copied: anything off the changed path is still shared, which is what makes this cheap and what makes reference equality a usable change check.
Freezing documents the intent, and only one level deep:
const config = Object.freeze({ retries: 3, nested: { debug: false } });
config.nested.debug = true; // allowed — nested was never frozen
console.log(config.nested.debug); // true
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value !== null && typeof value === 'object') deepFreeze(value);
}
return Object.freeze(obj);
}
const locked = deepFreeze({ nested: { debug: false } });
try {
locked.nested.debug = true; // TypeError in strict mode
} catch (error) {
console.log(error.constructor.name); // TypeError
}
Common mistakes
JSON.parse(JSON.stringify(x)) on real data
Mistake. Using it to clone anything containing dates, Maps or optional fields.
Why it fails. Dates become strings, Maps become {}, undefined properties disappear, and a
cycle throws. The failures are silent, so the bug surfaces far from the clone.
What to do instead. structuredClone, unless you specifically want JSON semantics.
A deep merge with no isPlainObject guard
Mistake. typeof value === 'object' as the test for “recurse into this”.
Why it fails. Arrays, Dates, Maps and class instances all pass, so they get walked key by key
and come out as broken plain objects — and null throws.
What to do instead. Check the prototype, and handle arrays with an explicit strategy.
Merging untrusted input without blocking __proto__
Mistake. A generic merge applied to a parsed request body.
Why it fails. A __proto__ key writes onto Object.prototype and affects every object in the
process.
What to do instead. Skip __proto__, constructor and prototype, or build the result with
Object.create(null).
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
Freezing an object raises the same depth question that copying one does.
This object was frozen, so why did the write succeed?
const o = Object.freeze({ a: 1, nested: { b: 2 } });
o.nested.b = 9;
console.log(o.nested.b); // 9What does JSON.parse(JSON.stringify(obj)) lose?
Every property carries flags behind it, not only a value.
What does this log?
const o = {};
Object.defineProperty(o, "a", { value: 1 });
console.log(o.a, Object.keys(o));Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.