简体   繁体   中英

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 ?

You can use the bracket notation property accessor:

 let keyName = 'key01'; let myObj = {}; myObj[keyName] = 'value01'; console.log(myObj);

For TypeScript, use:

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

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 want to change the value of your object using the variable keyName you can use the following.

 let keyName = "newValue"; let myObject = {keyName: "oldValue"} myObject.keyName = keyName console.log(myObject)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM