问题
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