Skip to content
GreenSnippets

Deep clone an object with structuredClone

Copy nested objects, arrays, Maps, Sets and Dates without sharing references, using the built-in structuredClone.

JavaScript
function deepClone(value) {
  return structuredClone(value);
}

Example / expected output

Output
const copy = deepClone({ when: new Date(0), tags: new Set(["a"]) });
copy.tags.add("b"); // the original Set is unchanged

How it works

structuredClone is built into modern browsers and Node.js 17+. Unlike JSON.parse(JSON.stringify(x)), it keeps Date, Map, Set, BigInt and circular references intact. It cannot clone functions or class methods, and throws a DataCloneError if it meets one.

  • JavaScript Tested

    Pick and omit object keys

    Build a new object with only some keys, or without some keys, without mutating the original.

  • JavaScript Tested

    Deep merge plain objects

    Recursively merge configuration objects without mutating the inputs and without prototype pollution.

  • JavaScript Tested

    Deep equality check

    Compare two values structurally, including nested objects, arrays, Dates, Maps and Sets.