I am building some objects in JavaScript and pushing these objects into an array, I store the key I want to use in a variable and then create my object like this:
var key = "happyCount"; myArray.push( { key : someValueArray } );
But when I try to check the object array for each object, the key is "key"
instead of the value of the variable key. Is there any way to set the value of a key from a variable?
Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/
In ES6, you can do this.
Its name is Computed property name, it is implemented using bracket notation (square brackets)
[]
Example:
{ [variableName] : someValue }
For ES5, try something like this
Example:
You need to create the object first and then set it using
[]
.2021 Update:
Computed Property NamesThe feature introduced in ECMAScript 2015 (ES6) allows you to dynamically compute the names of object properties in JavaScript object literal notation.