箭头函数返回的对象中出现"意外令牌"语法错误

Ant*_*ong 5 javascript ecmascript-6

这是有问题的代码:

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

我正在使用babel将es6代码翻译为javascript.这是错误消息:

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 |         }
Run Code Online (Sandbox Code Playgroud)

为什么会出现语法错误?

Mic*_*ski 8

在您的示例中,JavaScript处理{}作为块语句而不是对象文字.用括号(())包裹你的对象,它会工作.

更正代码:

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