I have:
var obj_a = {"A":1231,"B":34534,...};
var obj_b = obj_a;
for(var id in obj_b){
//do something
delete obj_b[id];
}
console.log(obj_b); // {}
console.log(obj_a); // {}
I don't want obj_a
is {}
How I can fix this?
Thank you!
I have:
var obj_a = {"A":1231,"B":34534,...};
var obj_b = obj_a;
for(var id in obj_b){
//do something
delete obj_b[id];
}
console.log(obj_b); // {}
console.log(obj_a); // {}
I don't want obj_a
is {}
How I can fix this?
Thank you!
This would help you.
We create obj_b
by copy obj_a value.
var obj_b = Object.assign({},obj_a);
For more information : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
What you want is to do a deep copy obj_a
and assign it to obj_b
like:
var obj_b = Object.assign({}, obj_a)
obj_a
is a reference to the object you created and hence the line obj_b = obj_a
is making a copy to the reference, not it's value. Therefore when you mutate the values of obj_b
in the for-loop, you are mutating the values to the reference obj_a
holds as well.
Edit: just had a look at thebenchmarks and noticed that Object.assign
is now faster than JSON.stringify