Search code examples
javascriptecmascript-6arrow-functionscomputed-properties

Create an object literal with ComputedPropertyName in arrow function


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 :


Solution

  • 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.