Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string varaible value as key name in object in Typescript

In Typescript I would like the myObj variable to be:

{'key01': 'value01'}

So I go ahead with:

let keyName = 'key01';
let myObj = {keyName: 'value01'};

console.log(myObj);

But the resulting variable is

{ keyName: 'value01' }

Can I use the value of the keyName variable to use as the key name for the variable myObj?

like image 939
alphanumeric Avatar asked Oct 25 '25 08:10

alphanumeric


1 Answers

If you don't want to waste space with an extra line of code for defining the main object and then defining the custom key, you can use bracket notation inline.

let keyName = 'key01';
let myObj = { [keyName]: 'value01' };

console.log(myObj);
like image 74
Samathingamajig Avatar answered Oct 27 '25 21:10

Samathingamajig