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?

3
  • If your object doesn't hold any circular references, I think it JSON.parse(JSON.stringify(obj)) is the way to go Commented Oct 8, 2019 at 13:48
  • Object.assign will keep references, the JSON.parse/JSON.stringify trick can really deepClone. Commented Oct 8, 2019 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.) Commented Oct 8, 2019 at 13:57

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.