How do I deep clone an object in JavaScript without JSON.parse(JSON.stringify())?
poze 4 months ago196 gadeen
I've been using JSON.parse(JSON.stringify(obj)) to clone state, but it breaks Date objects and drops undefined and Map values. Is there a built-in way now?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
2 Repons
Yes. structuredClone is built into all modern browsers and Node 17+:
const copy = structuredClone(original);
It correctly handles Date, Map, Set, RegExp, typed arrays, ArrayBuffer, and even circular references.
It can't clone functions, DOM nodes, or class prototypes: a class instance comes back as a plain object. If you need those, use a library like lodash.clonedeep, or rethink whether you need a deep clone at all. In React, immutable updates with spreads are usually enough.
Konekte pou di lòt moun si li te mache.
Often you don't need a *deep* clone. For updating nested state, a targeted shallow copy is cheaper and clearer:
const next = { ...state, user: { ...state.user, name: 'Ruth' } };
For very nested state, immer's produce lets you write mutations that produce an immutable copy.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.