variable as key in object javascript code example
Example 1: variable key name js
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
Example 2: javascript create object key from variable
{
[yourKeyVariable]: "yourValue",
}
var yourObject = {};
yourObject[yourKeyVariable] = "yourValue";
Example 3: javascript object as key
var fighters = new WeakMap();
var bruce = {name: 'Bruce Lee'};
var chuck = {name: 'Chuck Norris'};
fighters.set(bruce, 'Jeet Kune Do');
fighters.set(chuck, 'Karate');
console.log(fighters.get(bruce));
console.log(fighters.get(chuck));
Example 4: javascript variable as object key
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
Example 5: how to use variable in js key
ES6 defines ComputedPropertyName
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top);