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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With