Open In App

How to Clone a JavaScript Object?

Last Updated : 17 Nov, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Here are different methods to clone a JavaScript object.

1. Using Object.assign() Method

The Object.assign() method is used to clone the given object. We have assigned the given object to the new empty object by just using this method.

Syntax

let Clone_object =Object.assign({}, sourceObject);

Note: This method does only a shallow copy. It means that nested properties are still copied by reference.  


Output
{ a: 1, b: 2, c: 3 }

2. Using Spread Operator

This approaches uses Spread operator for the cloning of object. It assigned all the elements to the new object.


Output
{ a: 1, b: 2, c: 3 }

3. Using hasOwnProperty() Method

This approaches uses hasOwnProperty() Method. we have used a loop to iterate through the source object and assigning them to new object by using the hasOwnProperty() method.


Output
{ a: 1, b: 2, c: 3 }

4. Using JSON.stringify() Method

This approach uses JSON.stringify() Method to clone a JavaScript Object. We are parsing the JSON.stringify() object to JSON.parse() so that it can be cloned to new empty object.


Output
{ a: 1, b: 2, c: 3 }


Next Article

Similar Reads