最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin9浏览0评论

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?

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?

Share Improve this question edited Jan 29, 2018 at 4:23 Eddie 26.9k6 gold badges38 silver badges59 bronze badges asked Jan 29, 2018 at 4:21 nir segevnir segev 3581 gold badge4 silver badges12 bronze badges 2
  • Not wise for performance in a lot of cases, and has the risk of throwing a stack overflow if the object has cyclical references. – Patrick Roberts Commented Jan 29, 2018 at 4:27
  • 1 Possible duplicate of What is the most efficient way to deep clone an object in JavaScript? – Patrick Roberts Commented Jan 29, 2018 at 4:30
Add a ment  | 

2 Answers 2

Reset to default 5

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 remend checking out something like an underscore or a lodash for high-performance deep copying.

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.

发布评论

评论列表(0)

  1. 暂无评论