0

I need to reduce a JSON with objects with names and other properties down to only objects with names.

At first I used this but this resulted in a SyntaxError: Unexpected token ':':

data.map(m => {"name": m.name})

This works but I was wondering if there is a better way?

data.map(m => {
    return {"name": m.name}
})
Jan-Pieter
  • 137
  • 2
  • 10

1 Answers1

4

Wrap the curly brackets with parentheses, when you wish to return an object:

data.map(m => ({ "name": m.name }))

Since the names of the properties are the same, you can also use destructuring and shorthand property names:

data.map(({ name }) => ({ name }))
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Still looking forward to a shorthand of the second example `data.map(({ name }) => ({ name }))` which is kinda boilerplaty especially if you have to extract multiple properties without name change. – robsn Jun 07 '23 at 07:34