Anjan Dutta

Javascript deep clone an object

Javascript deep clone an object

Deep cloning duplicate everything. A deep clone of an object creates a second object with all of the elements in the original object duplicated.

let fruitObject = {name: 'Apple', color: 'Red'}
let fruitObj2 = JSON.parse(JSON.stringify(fruitObject));

This is the only way we can deep clone or deep copy an object using native Javascript.

But, this method is not lossless.

For example, if our object contains date objects then after converting to string and back to object will convert those date objects to simple strings.

Hence deep cloning an object using this method is not lossless. A solution is using libraries like lodash which is made for solving such problems.