Sometimes we need to have a copy of existing JavaScript object and work on it by modifying cloned copy and send or do some other operations without disturbing existing global object as it will use by different functionality throughout the page or application lifespan.

In JavaScript, we have two approaches to clone an existing object and each having its own advantages and disadvantages as discussing more below

Approach-1: Using JSON

In this approach, we can convert the given object as JSON string usingJSON.Stringify() method and then again convert to object using JSON.parse() method.

var _existingobject = {}; 
var _cloneobject = JSON.parse(JSON.stringify(_existingobject));

Here, this approach affects little performance as it is performing two operations one to make it valid JSON string and then again converting to JSON object. 

Approach-2: Using jQuery

In this approach, we utilize jQuery extend() method. Where it helps to merge two similar objects into one object by considering all properties in both the objects. This is mostly used in case if we have a set of default object and user sent object, where when we apply to extend() it will return an object with all the properties with default values for the properties which are not assigned any value by the user.

Here we don’t have the second object, so we can send an empty object and it will give us valid cloned object. Using this method we can do two types of clone one is shallow and another is a deep clone.

Shallow Clone: copies only high level properties

var _cloneObject = jQuery.extend({}, _existingObject);

Deep Clone: copies high level properties as well as its child properties and their child properties so on.

var _cloneObject = jQuery.extend(true, {}, _existingObject);

Hope it helps you 🙂