Setting a variable value as an object key in Javascript: The Simplest Way

Tagged: javascript
Photo by Pixabay from Pexels
Photo by Pixabay from Pexels

In Javascript, you sometimes may find yourself needing to assign an attribute to an object based off the value of another variable.

There are currently two ways of doing this:

What’s the old way? (Pre ES6)

The old way that you used to do this was to make the object first and then use bracket notation ([]) to set it.

var wantedKey = "timesJumped"
var person = {}

person[wantedKey] = 250
console.log(person) // Will output {"timesJumped": 250}

The new ES6 way to assign an object key

In ECMAScript 2015, the syntax to initialize objects now also supports Computed Property Names. So now you can put your expression into brackets and it will be used as the property name.

var wantedKey = "moneyCarried"
var person = { [wantedKey]: 1500 }
console.log(person) // Should output {"moneyCarried": 1500}

Profile picture

Written by who lives and works in Wisconsin building useful things, and thinks that pineapple on pizza is okay. You should follow them on Twitter