Consider below code
var obj={a:1,b:2};
var copiedObj=obj;
obj.a=3;
console.log(copiedObj.a); // 3
The question here is how can I change the values of obj without changing the values in copiedObj;
Consider below code
var obj={a:1,b:2};
var copiedObj=obj;
obj.a=3;
console.log(copiedObj.a); // 3
The question here is how can I change the values of obj without changing the values in copiedObj;
If you want to make a shallow copy of an object, you can use Object.assign:
const obj = {a:1,b:2};
const copiedObj = Object.assign({}, obj);
obj.a=3;
console.log(copiedObj.a); // 1
Note that this is only a shallow copy though, so if you have a deeply nested object, those nested references can still be the same. For example:
const obj = {
a: {
a: 1
},
b:2
};
var copiedObj = Object.assign({}, obj);
obj.a.a=3;
console.log(copiedObj.a.a); // 3
As an alternative to Object.assign, if you're using babel's transform-object-rest-spread transpiler (or if you're using a browser that supports it natively), you can do the same thing like this:
const obj = {a: 1, b: 2};
const copiedObj = {...obj};
obj.a = 3;
console.log(copiedObj.a); //1