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

Justin Lek picture Justin Lek · Jul 25, 2018 · Viewed 11.2k times · Source

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?

Answer

Denys Séguret picture Denys Séguret · Jul 25, 2018

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)