How do I deep clone an object in JavaScript without JSON.parse(JSON.stringify())?

poze 4 months ago197 gadeen

3

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.

poze 4 months ago

2 Repons

9
✓
✓ Repons yo aksepte

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.

answered 4 months ago
0

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.

answered 4 months ago

Sign in and verify your email to post an answer.