Clone a JS Object

Clone a JavaScript Object

 

In this example, you will learn to write a program that clones an object.

To understand this example, you should have the knowledge of the following JavaScript programming topics:

JavaScript Objects

JavaScript Object.assign()


A JavaScript object is a complex data type that can contain various data types. For example,


Here, person is an object. Now, you can't clone an object by doing something like this.



In the above program, the copy variable has the same value as the person object.

However, if you change the value of the copy object, the value in the person object will also change. For example,


The change is seen in both objects because objects are reference types.

And both <code>copy</code> and <code>person</code> are pointing to the same object.


Example 1. Clone the Object Using Object.assign()


The Object.assign() method is part of the ES6 standard. The Object.assign() method performs deep copy and copies all the properties from one or more objects.

Note: The empty {} as the first argument ensures that you don't change the original object.


Example 2: Clone the Object Using Spread Syntax



The spread syntax ... was introduced in the later version(ES6).

The spread syntax can be used to make a shallow copy of an object. This means it will copy the object.

Example 3: Clone the Object Using JSON.parse()


In the above program, the JSON.parse() method is used to clone an object.

Note: JSON.parse() only works with Number and String object literal. It does not work with an object literal with function or symbol properties.

Post a Comment

Previous Post Next Post