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;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.