I recently attempted a code challenge where I needed to deeply clone an object. Prior to this I learned to do this by converting it to JSON. But according to this blog post, he specifically has JSON Serialization as the wrong way to do this.
The reason for this is:
"By doing this you will lose any Javascript property that has no equivalent type in JSON, like Function or Infinity. Any property thatโs assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object.
Also, some objects are converted to strings, like Date objects for example (also, not taking into account the timezone and defaulting to UTC), Set, Map and many others"
Is there a native way to deeply clone an object in JavaScript? The only approach he listed is by using the Lodash library. All of the other methods are shallow copies.
Top comments (11)
A library is just a collection of solutions written in a way that they can be reusable. Here is the module in lodash that contains the logic for the deep clone github.com/lodash/lodash/blob/mast..., it's imported from this module github.com/lodash/lodash/blob/mast..., which is the module you would use in your code.
There seems to be no native way, but it is as simple as,
A perfect way is simply,
This is helpful. Thanks!!
Are you means?
test cases (mandatory true)
This is awesome! Thanks for also adding the test cases
If it's not a nested object, it's really nice to use the spread operator
const newObject = { ..currentObject };
If it's a nested or deeply nested object, it's much safer to use
const newObject = JSON.parse(JSON.stringify(currentObject))
in a nutshell:
const cloneDeep = (obj) => {
return JSON.parse(JSON.stringify(obj))
}
I should say i haven't taken the time to see any performance detriments, if any, appear.
cloning nested object is like diving into a black hole
let obj = {stuff: {
more_stuff: "this",
list: [1,2,3]},
}
JSON.parse(JSON.stringify(obj))
This is only a shallow clone so nested reference types would not be cloned
developer.mozilla.org/en-US/docs/W...