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

asked 4 months ago199 viewsen

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?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 4 months ago

2 Answers

9
✓
✓ Accepted answer

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.

Sign in to tell others whether this worked.

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.

Sign in to tell others whether this worked.

answered 4 months ago

Sign in and verify your email to post an answer.