-5

Can somebody tell me please what is wrong with this arrow function. It throws me an error

unexpected token on begin of if condition

selected_devices
  .map( device => if( device.device_id === device_id ) device.source = 'included' )
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Čamo
  • 3,863
  • 13
  • 62
  • 114

2 Answers2

2

You need {} when you have an if or other things that are not a single statement - also do NOT use map if you want forEach since map creates an unnecessary array you then throw away

selected_devices
  .forEach(device => device.source = device.device_id === device_id  ? 'included' : device.source)

or perhaps

selected_devices
  .filter( device => device.device_id === device_id)
  .forEach(device => device.source = 'included')
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

looks like you forgot to add brackets like this

selected_devices.map((device) => {
   if (device.device_id === device_id) device.source = 
   'included'
   return device
})

But you can also do with the ternary operator like this

selected_devices.map((device) =>
   device.device_id === device_id ? { ...device, device.source: 
   'included' } : device,
)
フィン
  • 21
  • 4
  • Brackets work with return, but it should not be necessary. – Čamo Mar 02 '22 at 08:40
  • @Čamo You need brackets if you want to use "if" because you can use if statements only in code blocks. If you don't want to use brackets and/or a return statement you can use the ternary operator. – フィン Mar 02 '22 at 08:43