Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the dangers of Deep-copying objects using JSON.parse(JSON.stringify(obj))?

Using JSON.parse(JSON.stringify(obj)) is an old trick i've seen used a lot for deep-copying objects. Does it create a truly 'deep-copy' of an object? Performance-wise, is it considered wise to use?

like image 287
nir segev Avatar asked Oct 19 '25 14:10

nir segev


2 Answers

The biggest problem with using this method to deep-copy an object is the fact the object must be JSON serializable. For example, the following object:

let obj = {
    func: function() {
        console.log("hello world!");
    }
}

Would not be copied properly since functions are not JSON serializable. There are many other issues as well, such as with cyclic references. This really only works for simple, plain objects and thus isn't a particularly good solution. I would recommend checking out something like an underscore or a lodash for high-performance deep copying.

like image 50
treyhakanson Avatar answered Oct 21 '25 04:10

treyhakanson


A few problems exist with the JSON.parse(JSON.stringify(obj))

The main issue for most developers is the loss of anything not part of the JSON spec

  • Any internal getters and setters will be lost.
  • Destruction of date objects (Dates will be converted to strings
  • Class prototypes will be lost.

The JSON method will also throw an exception when parsing circular references.

That said it does have some advantages for it:

  • Raw speed the JSON method wins out over even most shallow copy methods in benchmarks
  • Due to native implementation in the browser unlike a library it does not need to be shipped to the client, possibly also speeding up page load times.

As far as creating a truly deep copy of the object... it will be a truly deep copy as it will go as many levels into the object as it can, it won't be in that it will discard certain information, as outlined above.

like image 44
macdja38 Avatar answered Oct 21 '25 03:10

macdja38



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!