Deep Clone an Object in JavaScript
Published on
Last updated on
structuredClone (recommended)
The built-in structuredClone() handles nested objects, arrays, Date, Map, Set, RegExp, and circular references out of the box:
const original = { a: 1, b: { c: 2, d: [3, 4] }, date: new Date(), }; const cloned = structuredClone(original); console.log(cloned.b === original.b); // false console.log(cloned.date instanceof Date); // true
structuredClonedoes not copy functions, DOM nodes, or prototype chains. If your object contains those, use the manual approach below.
Manual Fallback
A recursive approach for environments without structuredClone or when you need custom logic:
function deepClone(obj) { if (obj === null || typeof obj !== 'object') { return obj; } if (Array.isArray(obj)) { return obj.map(deepClone); } return Object.fromEntries( Object.entries(obj) .map(([key, value]) => [key, deepClone(value)]) ); }
This manual version does not handle
Date,Map,Set, or circular references. PreferstructuredClone()when possible.