Home What is the most efficient way to deep clone an object in JavaScript?
Reply: 1

What is the most efficient way to deep clone an object in JavaScript?

Jeremy Banks
1#
Jeremy Banks Published in 2017-05-23 12:18:30Z

What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox.

I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.

I've also seen recursive copying functions with various flaws.
I'm surprised no canonical solution exists.

Jeremy Banks
2#
Jeremy Banks Reply to 2017-05-23 12:18:30Z

Note: This is a reply to another answer, not a proper response to this question. If you wish to have fast object cloning please follow Corban's advice in their answer to this question.


I want to note that the .clone() method in jQuery only clones DOM elements. In order to clone JavaScript objects, you would do:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

I also want to note that the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (trying to deep extend a DOM element, for example). It's used frequently in jQuery core and in plugins to great effect.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.681275 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO