How to Clone a JavaScript Object?
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.
const sourceObject = { a: 1, b: 2, c: 3 };
let Clone_object = {};
Clone_object = Object.assign({}, sourceObject);
console.log(Clone_object);
const sourceObject = { a: 1, b: 2, c: 3 };
let Clone_object = {};
Clone_object = Object.assign({}, sourceObject);
console.log(Clone_object);
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.
const sourceObject = { a: 1, b: 2, c: 3 };
let Clone_object = {};
Clone_object = {...sourceObject};
console.log(Clone_object);
const sourceObject = { a: 1, b: 2, c: 3 };
let Clone_object = {};
Clone_object = {sourceObject};
console.log(Clone_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.
const sourceObject = {a:1, b:2, c:3};
let Cloned_Object = {};
for (let prop in sourceObject) {
if (sourceObject.hasOwnProperty(prop)) {
Cloned_Object[prop] = sourceObject[prop];
}
}
console.log(Cloned_Object);
const sourceObject = {a:1, b:2, c:3};
let Cloned_Object = {};
for (let prop in sourceObject) {
if (sourceObject.hasOwnProperty(prop)) {
Cloned_Object[prop] = sourceObject[prop];
}
}
console.log(Cloned_Object);
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.
const sourceObject = { a: 1, b: 2, c: 3 };
let Cloned_object = {};
Cloned_object = JSON.parse(JSON.stringify(sourceObject));
console.log(Cloned_object);
const sourceObject = { a: 1, b: 2, c: 3 };
let Cloned_object = {};
Cloned_object = JSON.parse(JSON.stringify(sourceObject));
console.log(Cloned_object);
Output
{ a: 1, b: 2, c: 3 }