0

How I can assign name of the object as a variable $var1 using TypeScript

const $var1 = 'email';
data = [{
          name: 'John',
          $var1: 22 
       }];
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
John_123
  • 67
  • 8

2 Answers2

3

Use JS computed property

const $var1 = 'email';
data = [{
          name: 'John',
          [$var1]: 22 
       }];
snsakib
  • 1,062
  • 9
  • 14
2

You can insert variable as key using Object[variable] as follows.

const $var1 = 'email';

// -- First Way
const data = [{
  name: 'John',
}];
data[0][$var1] = 22;
console.log(data);

// -- Second Way
const result2 = [{
  name: 'John',
  [$var1]: 22
}];
console.log(result2);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39