UI Development, Uncategorized

Cloning In JavaScript Object

Definition :-

Cloning an object means assigning or copying the values of a variable (previously declared and assigned) to a newly declared variable (assigned now).

Copying objects in JavaScript can be a difficult part. You can perform a shallow copy or deep copy, most of the cases shallow copy is default behavior.

Shallow Copy :-

In a shallow copy, values are cloned, and objects references are copied , so if you edit an object property in the original object,

then it gets modified in copied object, since the referenced inner object is the same.

There are Three Ways to Clone Objects in JavaScript :-

 1)  Using Spread

 2) Using Object.assign

 3) Using JSON

1. Using Spread :-

Using spread will clone your object. Note this will be a shallow copy. This spread operator for cloning objects is in Stage Four.

So it is not officially in the specifications yet. So if you were to use this, you did not compile it with Babel

2. Using Object.assign :-

The Object.assign method copies all enumerable own properties from one or more source to a target object. It returns the target object.

 3. Using JSON :-

Here we are using the variable source value to clone it to a variable known as target.

Using JSON method as the source object must be JSON safe. So it need exception handling to keep it safe in case in which source object can not be convertible to JSON

 Deep Clone :-

It is used to copies all the fields, and makes copies of dynamically allocated memory pointed to the fields. And it copy occurs when an object is copied      along with the objects to which it refers.

Use Lodash :-

I suggest you to perform deep copy is rely on library that well tested, It is popular and carefully maintained Lodash.

It is a convenient clone and deepclone functions to perform the shallow and deep cloning.

It has best feature you can import single functions separately in our project to reduce size of the dependency.

Using iteration :-

This is one of the working solutions for Deep cloning but not best one as this will have to iterate each and every time you need to clone an object.

Cloning is done using iteration of the Variable and this works completely fine with Deep copy.


 

About The Author