Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a spread operator in a map arrow function in one line [duplicate]

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?

like image 716
Justin Lek Avatar asked Jul 25 '18 12:07

Justin Lek


People also ask

Does the spread operator create a copy?

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.

Does spread operator create a new object or point to the same old object?

The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object.

How do you copy an object using the spread operator?

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.

What spread operator returns?

In case of arrays,this method does not change the existing arrays but instead returns a new array.


1 Answers

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)
like image 183
Denys Séguret Avatar answered Sep 19 '22 13:09

Denys Séguret