How to deep copy JavaScript objects using structuredClone
By Flavio Copes
Learn how to deep-copy supported JavaScript values with structuredClone(), including circular references, and understand which values it cannot clone.
For years and years we’ve had to use weird workarounds to do a deep clone of a JavaScript object.
Many of those were bug prone.
Like doing JSON.parse(JSON.stringify(obj)), where dates become strings and values such as undefined can disappear.
Or worse, copying object properties by reference, introducing bugs down the road.
Today we can use the global structuredClone() function:
const original = {
createdAt: new Date(),
tags: new Set(['javascript', 'node'])
}
const copy = structuredClone(original)
The copy has its own nested objects. It also preserves supported types such as Date, Map, Set, typed arrays, and circular references.
It cannot clone everything. Functions, DOM nodes, and some platform-specific objects throw a DataCloneError. Property descriptors, getters, setters, and custom class prototypes are not preserved as you might expect either.
Use structuredClone() when you need an independent copy of supported data. If you only need to copy one level, the spread syntax is simpler:
const copy = { ...original }
structuredClone() is available in current browsers and supported Node.js releases.
Related posts about node: