DEV Community

Nazmul Hasan👻
Nazmul Hasan👻

Posted on

Nested object clone disaster!!!!!

I was just trying to clone a parameter and after some manipulation update the redux state. But some unwanted value is updating , cause the clone copied the reference of the object also. Normally we try to assign a value of an object to another via ,

let something= sourceObject
Enter fullscreen mode Exit fullscreen mode

But, it can mutate the source object sometime, if the object is nested. Another way of doing the clone is,

let something= {...sourceObject}
Enter fullscreen mode Exit fullscreen mode

Still same result. Also tried,

let something= Object.assign({},sourceObject)
Enter fullscreen mode Exit fullscreen mode

No change of the scenario. Then, lodash came to rescue,

let something= _.cloneDeep(sourceObject);
Enter fullscreen mode Exit fullscreen mode

Now, it's just cloning the object without mutating it.

Top comments (0)