snippetjavascriptTippending
JavaScript structuredClone for deep copying
Viewed 0 times
structuredClonedeep-copycloneDateMapcircular
Problem
JSON.parse(JSON.stringify(obj)) drops functions, dates, Maps, Sets, and undefined values. Spread only does shallow copy.
Solution
Use structuredClone() for proper deep copying:
const original = {
name: 'Alice',
date: new Date(),
regex: /pattern/g,
map: new Map([['key', 'value']]),
set: new Set([1, 2, 3]),
nested: { deep: { value: 42 } },
array: [1, [2, [3]]],
undef: undefined,
};
// structuredClone - handles all of the above:
const clone = structuredClone(original);
clone.nested.deep.value = 99;
console.log(original.nested.deep.value); // Still 42!
// What structuredClone handles:
// - Date, RegExp, Map, Set, ArrayBuffer, Blob
// - Nested objects and arrays
// - undefined values
// - Circular references!
// What it CANNOT clone:
// - Functions
// - DOM nodes
// - Symbols
// - Property descriptors (getters/setters)
// - Prototype chain
// Available in:
// - All modern browsers
// - Node.js 17+
// - Deno, Bun
// For older environments, fallback:
// const clone = JSON.parse(JSON.stringify(obj)); // Lossy
// Or use lodash: _.cloneDeep(obj);
const original = {
name: 'Alice',
date: new Date(),
regex: /pattern/g,
map: new Map([['key', 'value']]),
set: new Set([1, 2, 3]),
nested: { deep: { value: 42 } },
array: [1, [2, [3]]],
undef: undefined,
};
// structuredClone - handles all of the above:
const clone = structuredClone(original);
clone.nested.deep.value = 99;
console.log(original.nested.deep.value); // Still 42!
// What structuredClone handles:
// - Date, RegExp, Map, Set, ArrayBuffer, Blob
// - Nested objects and arrays
// - undefined values
// - Circular references!
// What it CANNOT clone:
// - Functions
// - DOM nodes
// - Symbols
// - Property descriptors (getters/setters)
// - Prototype chain
// Available in:
// - All modern browsers
// - Node.js 17+
// - Deno, Bun
// For older environments, fallback:
// const clone = JSON.parse(JSON.stringify(obj)); // Lossy
// Or use lodash: _.cloneDeep(obj);
Why
structuredClone is the standard API for deep cloning, handling types that JSON serialization drops. No library needed.
Revisions (0)
No revisions yet.