简体   繁体   English

如何在Typescript中使用字符串变量值作为对象中的键名

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

In Typescript I would like the myObj variable to be:在打字稿中,我希望myObj变量是:

{'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 ?我可以使用keyName变量的值作为变量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.如果要使用变量keyName更改对象的值,可以使用以下命令。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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