0

How to convert this:

const array = [10, 0, 90, 80, 50, 0, 60];
let id = 1;

const studentScores = array.map(function(score, index){
  return { [index]: score, student_id: id } 
});

console.log(studentScores)

Into fat arrow syntax:

const studentScores = array.map((score, index) => { [index]: score, student_id: id } );

My try throws an error:

SyntaxError: Unexpected token :

Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81

2 Answers2

4

You have to parenthesize the object literal to convince the parser that it is an object literal:

const studentScores = array.map((score, index) => ({ [index]: score, student_id: id }) );

By wrapping it in parentheses, the parser is forced to interpret it as an expression and not a statement block. The { character has that ambiguity, and when it's the first thing in a statement the parser always assumes "statement block" is what it's seeing.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

To implicitly return an object with arrow function, wrapp it with parentheses:

const studentScores = array.map((score, index) => ({ [index]: score, student_id: id }) );
Faly
  • 13,291
  • 2
  • 19
  • 37