Object Cloning in JavaScript
Object is a reference type in JavaScript. This means that whenever we try to assign the value of an object to another object, the new object merely points to the reference of the former object in memory. Once the former object is changed, the new object will persist those changes.
There are several ways of cloning an object in JavaScript. Some of them are listed below.
Using for-in loop
const obj1 = { a: 1, b: 2 };
const obj2 = { };
for(i in obj1) {
obj2[i] = obj1[i];
}
Using Object.assign()
const obj1 = { a: 1, b: 2 };
const obj2 = Object.assign({}, obj1);
Using Spread Operator
const obj1 = { a: 1, b: 2 };
const obj2 = {...obj1};
Using JSON.parse() & JSON.stringfy()
const obj1 = { a: 1, b: 2 };
const obj2 = JSON.parse(JSON.stringify(obj1));
Using Constructor Function
function ObjectClone(obj) {
this.a = obj.a;
this.b = obj.b;
}
const obj1 = { a: 1, b: 2 };
const obj2 = new ObjectClone(obj1);
There's a way of pointing to the original object's properties when the object pointing to the original one is itself empty. This can be achieved through Object.create().
const obj1 = { a: 1, b: 2 };
const obj2 = Object.create(obj1);
Note: obj2 in this case will remain empty. However, obj2.a will point to obj1.a, and so on..