Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Unexpected token' syntax error in object returned by arrow function [duplicate]

Here is the code in question:

const data =
  results.responses.map((response, idx) =>
    { id: idx+1,
      name: response.name,
      email: response.email,
      comment: response.comment
    }
  )

I am using babel to translate the es6 code to javascript. This is the error message:

Module build failed: SyntaxError: /Users/antkong/dev/project/form.js: Unexpected token (60:14)
  58 |       results.responses.map((response, idx) =>
  59 |         { id: idx+1,
> 60 |           name: response.name,
     |               ^
  61 |           email: response.email,
  62 |           comment: response.comment
  63 |         }

Why there is a syntax error there?

like image 543
Anthony Kong Avatar asked Jan 09 '16 22:01

Anthony Kong


1 Answers

In your example JavaScript treats { and } as a block statement instead of object literal. Wrap your object in brackets (( and )) and it will work.

Corrected code:

const data =
  results.responses.map((response, idx) =>
    ({ id: idx+1,
      name: response.name,
      email: response.email,
      comment: response.comment
    })
  )
like image 188
Michał Perłakowski Avatar answered Oct 19 '22 00:10

Michał Perłakowski