top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+5 votes
499 views
What is the most efficient way to clone an object in Javascript?
posted Mar 31, 2015 by Merry

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

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.

answer Apr 17, 2015 by Vrije Mani Upadhyay
Similar Questions
+2 votes

Which is the most efficient (i.e. processing speed) way to create a server application that accesses a database: A Servlet using JDBC; a JSP page using a JavaBean to carry out the db access; or JSP combined with a Servlet? Are these my only choices?

+2 votes

What is the best way to detect a mobile device in JavaScript? (Sample code would be helpful).

...