I used JSON.parse(JSON.stringify(obj)) and my Dates became strings and undefined values vanished. What should I use for a proper deep copy?
#javascript#structuredclone#objects
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
I used JSON.parse(JSON.stringify(obj)) and my Dates became strings and undefined values vanished. What should I use for a proper deep copy?
#javascript#structuredclone#objects
Use structuredClone, available in all current browsers and in Node.js 17+.
const original = {
when: new Date(),
tags: new Set(['a', 'b']),
map: new Map([[1, { x: 1 }]]),
nested: { list: [1, 2, 3] },
};
const copy = structuredClone(original);
copy.nested.list.push(4);
original.nested.list; // [1, 2, 3], untouched
copy.when instanceof Date; // true
Primitives, plain objects, arrays, Date, RegExp, Map, Set, ArrayBuffer/typed arrays, Error objects and circular references.
DataCloneError).JSON.parse(JSON.stringify(x)) converts Dates to strings, drops undefined, functions and symbols, turns NaN/Infinity into null, and throws on circular structures or BigInt.
{ ...obj }, [...arr], Object.assign. Only top-level properties are copied, nested objects are shared.const next = { ...state, user: { ...state.user, name: 'New' } };
clone() method or use a library (lodash.clonedeep).Pitfall: cloning huge objects on every keystroke is slow. Consider structural sharing (spread only the changed path) or Immer.