How to Clone an Object in JavaScript

From WikiHTP

The scripting language does not provide a method for cloning an object. But, there are nevertheless solutions to the problem.

The only clone method that exists only works for DOM elements. We must either use other JavaScript functions or use external libraries that provide these methods, jQuery for example.

Using JSON[edit]

The fastest way to clone a simple object is to use the JSON language. The JSON.stringify() method transforms an object into a character string in JSON format, while the JSON.Parse() method performs the opposite operation. By combining these two methods, we obtain a cloning method for an object:

var myNewObject = JSON.parse(JSON.stringify (myObject));

Although this method works for simple objects, it has limitations. The date format attributes will not be converted correctly, the JSON.stringify() method will turn a date object into a string with the date in ISO format. In addition, the JSON language cannot handle functions. This method will not work for an object that has methods.

Using jQuery extend() Method[edit]

The JQuery JavaScript library provides the extend() method that can merge the contents of two objects. By sending it an empty object in one of the two parameters, we obtain a method to clone an object.

var myNewObject = jQuery.extend({}, myObject);

This method defaults to a surface copy of the object, that is, it copies the attributes and methods without copying other objects that might be contained in the original object. However, it is possible to make a deep copy to obtain an exact clone of the starting object. This must be true in the first parameter.

var myNewObject = jQuery.extend (true, {}, myObject);

If you want a faster method and you know the structure of your object, the most effective way is to build your clone yourself with a method specific to your class. Indeed, cloning methods use many loops to browse the object and the hasOwnProperty() method to verify that the object has a property. The JavaScript runtime will take longer to run a generic clone method than a specific clone method.

About This Tutorial

This page was last edited on 28 January 2019, at 06:34.