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

时光怂恿深爱的人放手 提交于 2019-12-11 02:24:58

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/49068757/can-i-use-template-string-on-object-key-in-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!