Your friend John's digital garden

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].


Tuesday Brew

Curated finds from my week, mostly about coding, job opportunities and whatever else catches my eye. I also include new posts to my digital garden.

    I won’t send you spam.

    Unsubscribe at any time.

    Written by John Omar who lives and works remotely building useful things. You should follow him on Twitter