What I need to do is map over an Array and set a value to false on all of the objects. This was my first shot:
data = data.map((item) => {
item.active = false;
return item;
})
Works! But then there is Eslint, no-param-reassign. So I had to find something else. After some googling I found the spread operator! Awesome! I created this masterpiece:
data = data.map((item) => {
return {...item, active: false}
})
Looks cool and works as well. But then there is Eslint again, arrow-body-style. ok fine I will return the object on the same line:
data = data.map(item => {...item, active: false});
Dosn't work! :'( Am I missing something?
The spread operator makes deep copies of data if the data is not nested. When you have nested data in an array or object the spread operator will create a deep copy of the top most data and a shallow copy of the nested data.
The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object.
So you use the spread operator to it to take its value out, which is a primitive data typed value (10), then you use {a : X } as this to make a new object. Basically it goes like this a : {... {b: 10}} -> a : {b: 10}, meaning you get the same object with a deep copy.
In case of arrays,this method does not change the existing arrays but instead returns a new array.
When returning a literal object from an arrow function construct (a lambda), you have to wrap it in parentheses so that it's seen as an expression:
data.map(item => ({...item, active: false}));
map
is only useful if you need a different array.
But there's a simpler solution here. You don't have to reassign all items and data
. You should simply do
data.forEach(item => item.active=false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With