4

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?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

3 Answers3

5

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);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
1

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';
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • Is it designed to run in Javascript or Typescript? Typescript raises an error – alphanumeric Jul 14 '21 at 02:15
  • ```Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'. let keyName: string``` – alphanumeric Jul 14 '21 at 02:15
0

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)
  • OP wanted the resulting object to be { key01: "value01" }, based off of the dynamic naming of the value of `keyName`. This is just creating an object with a static key name of `keyName` and assigning it the value `"oldValue"`, then reassigning it to have the value `"newValue"` – Samathingamajig Jul 14 '21 at 14:34