0

I have two variables. One variable gets set to the other, but I would like to assign the value, not the pointer. According to Microsoft's Javascript Docs, a variable, when assigned, is set to the same pointer of the source variable.

Here is a boiled-down version of my code:

var foo = { "baz": "qux" };
var bar = foo;
foo.baz = "quuz";
console.log(foo); // should equal {"baz": "quuz"}
console.log(bar); // should equal {"baz": "qux"}

Is there an easy, straightforward way to do this? If so, I can't find any documentation of it.

yummypasta
  • 1,398
  • 2
  • 17
  • 36
  • Copy the object. Quick, dirty and not optimized for performance: `var bar = JSON.parse(JSON.stringify(foo));` Search for shallow/deep cloning of JavaScript objects for alternatives. – Robby Cornelissen Dec 05 '17 at 03:53
  • Please use Object.assign instead.So you have to write var bar = Object.assign({},foo);This would serve the purpose.Please read through this:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – Sunil Hari Dec 05 '17 at 03:59
  • @Shadow Worth noting that `Object.assign()` will only create a shallow copy. – Robby Cornelissen Dec 05 '17 at 04:02
  • Wont that serve @yummypasta's purpose?? – Sunil Hari Dec 05 '17 at 04:07

0 Answers0