-3

How do I use template literal as key inside object literal?

The following code:

{
    `${id}_name`: "John Doe",
    `${id}_age`: 27,
}

Produces a syntax error:

Uncaught SyntaxError: Unexpected token :

Is there something I'm missing, or is this not supported? If not, is support for this feature planned?

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • 3
    You might need `[]`? Like this `{ [\`${id}_name\`]: "John Doe" }` – evolutionxbox Jan 17 '20 at 17:13
  • 3
    Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – ASDFGerte Jan 17 '20 at 17:13
  • @evolutionxbox Thanks, just figured that out myself. – David Callanan Jan 17 '20 at 17:14
  • Why the downvotes, and why the close? This question could be very useful for further readers. This *question* is not a duplicate, the *answers* in the "similar question" just happen to apply to this situation too. – David Callanan Jan 17 '20 at 17:37

2 Answers2

3

And of course I come up with a solution straight away:

{
    [`${id}_name`]: "John Doe",
    [`${id}_age`]: 27,
}

Wrap the template literal in square brackets. This will evaluate the expression in between the square brackets and use it as the key.

Without square brackets, only identifiers (e.g. my_key_name), single or double quote strings (e.g. "My Key Name") and numbers (e.g. 42) can be used.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
1

Your answer is correct, but i will try to answer the why of it.

If we refer to the Ecmascript object definition, it is said

Properties are identified using key values. A property key value is either an ECMAScript String value or a Symbol value. All String and Symbol values, including the empty String, are valid as property keys. A property name is a property key that is a String value.

In this case, a ECMAScript string is defined as

A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED).

Which mean a string has to be unicode caracter enclosed in single or double quotes. And Object keys must be ECMAScript string or Symbol, which i assume are index.

A template literal is a ECMAScript string but an ECMAScript string is not a template literal.

P.S. Take this with a grain of salt, i'm not an ECMAScript expert but that's what i could find.

Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • 1
    Actually, i think [Bergi](https://stackoverflow.com/a/35902149/5784924) has a better explanation on the subject. – Nicolas Jan 17 '20 at 17:24