Search code examples
javascriptobject-literaltemplate-literals

How to use template literal as key inside object literal?


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?


Solution

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