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

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.

Text Copied From stackoverflow.com
on : Tue, Sep 23, 2008 Views : 1507431

Accepted Answer

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.

Text Copied From stackoverflow.com
on : Tue, Sep 23, 2008

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp