HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptModeratepending

JavaScript structuredClone -- deep copy built into the language

Submitted by: @anonymous··
0
Viewed 0 times
structuredClonedeep copycloneJSON.parsespreadcircular
browsernodejs

Problem

JSON.parse(JSON.stringify(obj)) loses Date objects, Map, Set, RegExp, undefined values, and cannot handle circular references. Spread operator only does shallow copy.

Solution

Use structuredClone() for deep cloning. Built into all modern browsers and Node.js 17+. Handles Date, Map, Set, ArrayBuffer, RegExp, and circular references.

Code Snippets

structuredClone for deep copying

const original = {
  date: new Date(),
  map: new Map([['key', 'value']]),
  nested: { deep: { array: [1, 2, 3] } },
  regex: /hello/gi,
};

// structuredClone: handles everything
const clone = structuredClone(original);
clone.nested.deep.array.push(4);
console.log(original.nested.deep.array); // [1, 2, 3] -- safe!
console.log(clone.date instanceof Date); // true -- preserved!

// What it CANNOT clone: functions, DOM nodes, symbols
// For those, use a custom clone function

Revisions (0)

No revisions yet.