Computer >> Computer tutorials >  >> Programming >> Javascript

How would you deep copy an Object in Javascript?


A deep copy of an object duplicates every object it encounters within the object we want to copy. The copy and the original object will not share anything, so it will be a copy of the original.

The easiest way is to convert the object to JSON string and convert it back to a JS object. This way however doesn't allow method copying.

Example

let obj = {
   foo: 1,
   bar: { baz: 'test' }
}
let newObj = JSON.parse(JSON.stringify(obj));
obj.bar.baz = 20;
console.log(obj);
console.log(newObj);

Output

{ foo: 1, bar: { baz: 20 } }  
{ foo: 1, bar: { baz: 'test' } } 

The newObj here doesn't change with update to original obj, so deep copying was successful.