6

What is wrong with this expression?

['a', 'b'].map((x) => {[x]:x})

I'm getting this error:

Uncaught SyntaxError: Unexpected token :

3 Answers3

7

You need to wrap your {} in (), or it will be interpreted as the body of a function:

['a', 'b'].map((x) => ({[x]: x }))
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • This is the correct answer. As a side note, for clarity, I often wrap the returned object like this: `['a', 'b'].map((x) => Object({[x]: x}))` – zfrisch Jun 26 '18 at 15:17
4

You have enclosed the return value with ()

let result = ['a', 'b'].map((x) => ({[x]: x}));

console.log(result);
Eddie
  • 26,593
  • 6
  • 36
  • 58
4

whenever you return object from arrow functions you wrap them in paranthesis

['a', 'b'].map((x) => ({[x]:x}))

ashish singh
  • 6,526
  • 2
  • 15
  • 35