The Best Way to Deep Clone an Object in JavaScript
If you want to clone an object deep in JavaScript, there are several ways to do it.
The modern way
With the structuredClone API there is a new possibility to clone deep objects.
const myExampleObject = {
name: 'Max',
age: 30,
hobbies: ['Sports', 'Cooking'],
address: {
street: 'Mainstreet 1',
city: 'Berlin',
},
};
const myExampleObjectClone = structuredClone(myExampleObject);
The classic way
Make a deep clone with JSON.stringify and JSON.parse.
const myExampleObject = {
name: 'Max',
age: 30,
hobbies: ['Sports', 'Cooking'],
address: {
street: 'Mainstreet 1',
city: 'Berlin',
},
};
const myExampleObjectClone = JSON.parse(JSON.stringify(myExampleObject));
The self-made way
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
const myExampleObject = {
name: 'Max',
age: 30,
hobbies: ['Sports', 'Cooking'],
address: {
street: 'Mainstreet 1',
city: 'Berlin',
},
};
const myExampleObjectClone = deepClone(myExampleObject);
⚠️ How a deep clone of an object doesn't work
Object.assign
Object.assign copies only the own properties of the object.
Spread syntax
The Spread syntax ... copies only the own properties of the object.
Get the code for these examples with the following gist 👇