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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With