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
?
- 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
3 Answers
Reset to default 6If 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)