nir segev
nir segev

Reputation: 358

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?

Upvotes: 4

Views: 3657

Answers (2)

macdja38
macdja38

Reputation: 613

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.

Upvotes: 3

treyhakanson
treyhakanson

Reputation: 4911

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.

Upvotes: 5

Related Questions