Syntax error "Unexpected token" in the object returned by the arrow function

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 es6 code into javascript. This error message is:

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 is there a syntax error?

+4
source share
1 answer

In your example, JavaScript handles {and }as a unit operator instead of an 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
    })
  )
+7
source

Source: https://habr.com/ru/post/1623599/


All Articles