![]() |
VOOZH | about |
Here are different methods to clone a JavaScript object.
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.
{ a: 1, b: 2, c: 3 }
This approaches uses Spread operator for the cloning of object. It assigned all the elements to the new object.
{ a: 1, b: 2, c: 3 }
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.
{ a: 1, b: 2, c: 3 }
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.
{ a: 1, b: 2, c: 3 }