-1

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!

Omega P
  • 197
  • 1
  • 20
  • 2
    Possible duplicate of [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Psidom Jul 10 '17 at 02:37

2 Answers2

1

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

Natsathorn
  • 1,530
  • 1
  • 12
  • 26
0

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

jurvis
  • 61
  • 3