StructuredClone For Deep Copies

Clone nested data with structuredClone instead of JSON round-trips — Dates, Maps, Sets, and cycles survive the copy intact.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
const original = {
  id: 7,
  createdAt: new Date('2026-11-17T10:00:00Z'),
  tags: new Set(['alpha', 'beta']),
  meta: new Map([['region', 'eu']]),
  nested: { deep: { value: 1 } },
};

// structuredClone:保留 Date/Map/Set,支持循环引用
const copy = structuredClone(original);
copy.nested.deep.value = 99;
copy.tags.add('gamma');

console.log('original deep:', original.nested.deep.value);
console.log('copy deep:', copy.nested.deep.value);
console.log('original tags size:', original.tags.size);
console.log('copy is Date:', copy.createdAt instanceof Date);
console.log('copy map region:', copy.meta.get('region'));

// JSON 往返的对照:Date 退化成字符串、Map/Set 直接丢失
const viaJson = JSON.parse(JSON.stringify(original));
console.log('json copy createdAt type:', typeof viaJson.createdAt);
console.log('json copy tags:', viaJson.tags);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

original deep: 1
copy deep: 99
original tags size: 2
copy is Date: true
copy map region: eu
json copy createdAt type: string
json copy tags: {}

How it works

Module-level bindings hold the data — original, copy, viaJson — with no function scope in between.

Applying it

Running the file prints labeled results such as original deep:, copy deep:, original tags size: — each operation’s effect is visible in the output.

Statements that matter

const viaJson = JSON.parse(JSON.stringify(original));
const copy = structuredClone(original);

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `original`, `copy`, `viaJson`.