What’s the fastest alternative to
JSON.parse(JSON.stringify(x))
There must be a nicer/built-in way to perform a deep clone on objects/arrays, but I haven’t found it yet.
Any ideas?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, there is no build in way to deep clone objects.
And deep cloning is a difficult and edgey thing to deal with.
Lets assume that a method
deepClone(a)should return a “deep clone” of b.Now a “deep clone” is an object with the same [[Prototype]] and having all the own properties cloned over.
For each clone property that is cloned over, if that has own properties that can be cloned over then do so, recursively.
Of course were keeping the meta data attached to properties like [[Writable]] and [[Enumerable]] in-tact. And we will just return the thing if it’s not an object.
This will fail for a lot of edge cases.
Live Example
As you can see you can’t deep clone objects generally without breaking their special properties (like
.lengthin array). To fix that you have to treatArrayseperately, and then treat every special object seperately.What do you expect to happen when you do
deepClone(document.getElementById("foobar"))?As an aside, shallow clones are easy.