Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object literal dynamic key SyntaxError [duplicate]

What is wrong with this expression?

['a', 'b'].map((x) => {[x]:x})

I'm getting this error:

Uncaught SyntaxError: Unexpected token :
like image 281
Guilherme Nemeth Avatar asked Jun 26 '18 15:06

Guilherme Nemeth


3 Answers

You need to wrap your {} in (), or it will be interpreted as the body of a function:

['a', 'b'].map((x) => ({[x]: x }))
like image 57
Tholle Avatar answered Oct 12 '22 09:10

Tholle


You have enclosed the return value with ()

let result = ['a', 'b'].map((x) => ({[x]: x}));

console.log(result);
like image 33
Eddie Avatar answered Oct 12 '22 08:10

Eddie


whenever you return object from arrow functions you wrap them in paranthesis

['a', 'b'].map((x) => ({[x]:x}))

like image 4
ashish singh Avatar answered Oct 12 '22 09:10

ashish singh