1

I want to take a Javascript object and convert it into an array of hashes.

The following works to get just one element of the object and turn it into an array:

const coordinatesArray = items.map((item) => item.latitude)

Returns: [51.5165328979492, 51.5990409851074, 51.5990409851074, 51.5165328979492, 51.5098190307617, 51.5128326416016, 51.5098190307617, 51.501766204834, 51.514087677002, 51.4983825683594, 51.5294952392578, 51.5123977661133, 51.5011863708496, 51.5204887390137, 51.514087677002, 51.5117797851562, 51.5139465332031]

But when I try to create hash elements to make up the array, I get an error:

const coordinatesArray = items.map((item) => { x:item.latitude, y:item.longitude })

Returns: Uncaught Error: Module build failed: SyntaxError: Unexpected token, expected ;

What am I doing wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
daveanderson88
  • 327
  • 1
  • 4
  • 12

3 Answers3

3

You need some parenthesis around the curly brackes, otherwise it is interpreted as block statement in arrow functions.

const coordinatesArray = items.map((item) => ({ x: item.latitude, y: item.longitude }));

Shorter with destructuring and short properties:

const coordinatesArray = items.map(({ latitude: x, longitude: y }) => ({ x, y }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

Try the following:

const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))

Lambda functions returning objects need an extra bracket set () to distinguish them from a function body.

Jacopo Lanzoni
  • 1,264
  • 2
  • 11
  • 25
0

Parenthesize the body of function to return an object literal expression:

 params => ({foo: bar}) 

In your case:

const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))

More Info here.

palaѕн
  • 72,112
  • 17
  • 116
  • 136