alphanumeric
alphanumeric

Reputation: 19329

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?

Upvotes: 4

Views: 3868

Answers (3)

Kenny Raye Canillo
Kenny Raye Canillo

Reputation: 7

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)

Upvotes: -1

Samathingamajig
Samathingamajig

Reputation: 13245

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

Upvotes: 6

Spectric
Spectric

Reputation: 31987

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

Upvotes: 1

Related Questions