Set Dynamic Object Keys in ES6 Javascript
August 24, 2020
The “old” way
const name = 'John'
const ageMap = {
'Fred': '20',
'Matt': '34'
}
ageMap[name] = 40
That would create a key in the object with the value of the variable name
and set it to 40.
The ES6 way
const name = 'John'
const ageMap = {
'Fred': '20',
'Matt': '34',
[name]: 40
}
All you do is wrap the variable in square brackets: [name]
.