constset=newSet([{id:1,color:"blue"},{id:2,color:"red"},{id:3,color:"green"}]);constarr=[...set];arr[0].color="purple";console.log(set);// check the first entry// or set.values().next().value.color
The conclusion is: spreading results in a shallow copy.
That means, copying primitive values turns fine. What you can do in case of objects copy, is to make a copy of those underlying objects:
constarr2=[...set].map(item=>Object.assign({},item));arr2[0].color="yellow";console.log(set);// check the first entry
But how about nested objects? Try this:
constset=newSet([{id:1,color:"blue",details:{weight:10}},{id:2,color:"red",details:{weight:20}},{id:3,color:"green",details:{weight:30}}]);constarr2=[...set].map(item=>Object.assign({},item));arr2[0].details.weight=12;console.log(set);// check the first entry
The conclusion is: Object.assign copies property values only (not a deep copy).
But wouldn't
spread
be creating a true new copy? -- do you mind expanding your thought, might be something helpful to include in my code notes ๐ตTry this:
The conclusion is: spreading results in a shallow copy.
Source: stackoverflow.com/questions/500511...
That means, copying primitive values turns fine. What you can do in case of objects copy, is to make a copy of those underlying objects:
But how about nested objects? Try this:
The conclusion is:
Object.assign
copies property values only (not a deep copy).Source: developer.mozilla.org/en-US/docs/W...
Conclusions:
- spreading results in a shallow copy
-
Object.assign
copies property values only (not a deep copy)