Using a variable as a key in an object literal in Javascript ES6

Written politely 2018-06-22.

Problem:

So, you want to use a variable to dynamically generate a key in a javascript object?

Solution:

It is actually pretty simple. Wrap your key name in [] and you should be good to go. If you want to use a default string append or prepend, that is simple, too using ES6.

const variablePrepend = 'Value Should Be';
const variableKeyArray = ['How about a ', 'Have you seen this ', 'Just look at a'];
const variableValue = 'purple alligator?';
const newObject = {
    [variableKeyArray[0]]: variableValue,
    [variableKeyArray[1]]: variableValue,
    [variableKeyArray[2]]: variableValue,
}
console.log('newObject looks like: ', newObject);

You could use any value as the variableKeyArray, but this example show how to use a variable to get the elements of an array. There are better ways to actually generate this code, but this implementation is just to illustrate the use of a variable as a key in an object literal in JavaScript.


Lucas McDaniel

Husband, father, teacher, musician, avid gamer, nature enthusiast, and passionate about the human condition.