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.
Code
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 earlyreturnwhen 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.