What is the most efficient way to deep clone an object in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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.

raja
Published on 18-Sep-2019 13:48:25
Advertisements