DEV Community

Discussion on: 6 Use Cases of Spread with Array in JavaScript

Collapse
 
penge profile image
Pavel Bucka

Try this:

const set = new Set([{ id: 1, color: "blue" }, { id: 2, color: "red" }, { id: 3, color: "green" }]);

const arr = [...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.

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:

const arr2 = [...set].map(item => Object.assign({}, item));
arr2[0].color = "yellow";

console.log(set); // check the first entry

But how about nested objects? Try this:

const set = new Set([{ id: 1, color: "blue", details: { weight: 10 } }, { id: 2, color: "red", details: { weight: 20 } }, { id: 3, color: "green", details: { weight: 30 } }]);

const arr2 = [...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).

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)