最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use string varaible value as key name in object in Typescript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Jul 14, 2021 at 2:00 alphanumericalphanumeric 19.4k74 gold badges277 silver badges422 bronze badges 3
  • I think you need this stackoverflow./questions/13391579/how-to-rename-json-key – Amit Verma Commented Jul 14, 2021 at 2:03
  • Please post it as an answer so we could up vote it – alphanumeric Commented Jul 14, 2021 at 2:05
  • this can not be posted as answer. if this was helpful you can mark it as helpful ment. – Amit Verma Commented Jul 14, 2021 at 2:06
Add a ment  | 

3 Answers 3

Reset to default 6

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);

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 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)

发布评论

评论列表(0)

  1. 暂无评论