0

I found out about computed property names here. In the given example, computed property names are used on an object that is subsequently stored as a variable.

When I try to use computed property names in an object that is returned as is, for example from within a map function, I get Uncaught SyntaxError: unexpected token: ':'.

Am I overlooking something or is this simply not possible without storing the object in a variable first.

Here is my code snippet

const values = [['foo1', { value: 1 }], ['foo2', { value: 2 }], ['foo3', { value: 3 }]];
values.map(([key, { value }]) => { [`${value}`]: key });
asiannoob
  • 33
  • 4
  • 2
    you missed brackets ```({ [`${value}`]: key })```. btw what are you trying to get – cmgchess Mar 27 '23 at 11:57
  • @cmgchess - FYI, if you start and end that code span with three backticks instead of one, you can use single backticks within it. But no need for the template literal at all: ```const values = [['foo1', { [value]: 1 }], /*...*/];``` :-) – T.J. Crowder Mar 27 '23 at 12:01
  • 1
    @​asiannoob - no need for the template literal in ```[`${value}`]: ___```, just `[value]: ___` is sufficient, `value`'s value will automatically be converted to string (unless it's a Symbol, since Symbols can be property keys [and in that case, the template literal would cause an error anyway because Symbols can't be *implicitly* converted to strings]). – T.J. Crowder Mar 27 '23 at 12:02
  • @cmgchess - you are right! I thought that returning the object directly (without the parentheses) would have been sufficient... I was trying to reverse map the properties of an object in 1 line haha. I.e. `{ propName: { code: propValue} }` -> `{ code: propName }` – asiannoob Mar 27 '23 at 12:03

0 Answers0