1

Object.assign doesn't deep copy an object. considering following code it should print 0 0 0 1 but it is printing 0 0 1 1.

var obj = {
  "value": {
    "default": 0
  }
};
var newo = Object.assign({}, obj);

console.log(obj.value.default);
console.log(newo.value.default);

newo.value.default = 1;

console.log(obj.value.default);
console.log(newo.value.default);

I know we can use JSON.parse(JSON.stringify(obj)). but is that a best practice solution?

Taki
  • 17,320
  • 4
  • 26
  • 47
Rashmin Javiya
  • 5,173
  • 3
  • 27
  • 49
  • If your object doesn't hold any circular references, I think it `JSON.parse(JSON.stringify(obj))` is the way to go – Ayrton Oct 08 '19 at 13:48
  • Object.assign will keep references, the JSON.parse/JSON.stringify trick can really deepClone. – Maxime Girou Oct 08 '19 at 13:49
  • 1
    Be careful, though: the JSON stringify/parse method will fail if your object contains circular references *or* any values that are not primitive types (so functions, instances of other classes, etc.) – IceMetalPunk Oct 08 '19 at 13:57

0 Answers0