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

posée 4 months ago199 vuesen

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?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 4 months ago

2 réponses

9
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

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.

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.