patternjavascriptCritical
JavaScript set object key by variable
Viewed 0 times
keyobjectsetvariablejavascript
Problem
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
but when I try to examine my array of objects for every object the key is
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
var key = "happyCount";
myArray.push( { key : someValueArray } );but when I try to examine my array of objects for every object the key is
"key" instead of the value of the variable key. Is there any way to set the value of the key from a variable? Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
Solution
You need to make the object first, then use
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
[] to set it.var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}Code Snippets
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}Context
Stack Overflow Q#11508463, score: 3085
Revisions (0)
No revisions yet.