Reputation: 358
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
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
The JSON method will also throw an exception when parsing circular references.
That said it does have some advantages for it:
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
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