Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Template String on object key in ES6? [duplicate]

Can I create an object passing the key value as template string?

const key = 'my-key', value = 'my-value'
const obj = {
  `${key}`: value 
}

Is there an alternative to do this?

like image 470
Hemã Vidal Avatar asked Nov 27 '22 08:11

Hemã Vidal


1 Answers

You have to use computed property syntax:

const key = 'my-key', value = 'my-value'
const obj = {
  [`${key}`]: value 
}

Note that if you just want to use a variable as key, you can write [key]: value.

like image 127
Michał Perłakowski Avatar answered Dec 04 '22 06:12

Michał Perłakowski