Deep Clone Plain Data Objects

Clone nested objects and arrays without sharing references, using the structured clone algorithm so dates, maps, and cycles are handled correctly.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
export function deepClone(value) {
  if (typeof structuredClone === "function") {
    return structuredClone(value);
  }
  if (value === null || typeof value !== "object") return value;
  if (Array.isArray(value)) return value.map((item) => deepClone(item));
  if (value instanceof Date) return new Date(value.getTime());
  const output = {};
  for (const key of Object.keys(value)) {
    output[key] = deepClone(value[key]);
  }
  return output;
}

What the code does

Count the function deepClone as the entire surface area of Deep Clone Plain Data Objects.

The one repetition in this snippet is the loop for (const key of Object.keys(value)).

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • The guard typeof structuredClone === "function" short-circuits the flow with an early return when its condition holds.

Using it

Entry signature: export function deepClone(value)

Import deepClone from the file and call it — the rest of the code is implementation detail.

Key statements

if (Array.isArray(value)) return value.map((item) => deepClone(item));
return structuredClone(value);
if (value === null || typeof value !== "object") return value;

Interactive Tools for This Topic

FAQ

Does `deepClone` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `deepClone` at load time.