Key for javascript dictionary is not stored as value but as variable name
Solution 1:
Try like this:
var obj = {};
obj[varName] = varValue;
You can't initialize objects with 'dynamic' keys in old Javascript. var obj = { varName : varValue };
is equivalent to var obj = { "varName" : varValue };
. This is how Javascript interprets.
However new ECMAScript supports computed property names, and you can do:
var obj = { [varName]: varValue };
Solution 2:
Starting with ECMAScript 2015, which has gotten better browser support in the last year(s), you can use the variable index notation:
const obj = { [varName] : varValue };
This is syntactically the same as
var obj = {};
obj[varName] = varValue;
You can also use expressions or Symbols as property key:
const contact = {
company: companyName,
};
const companiesWithContacts = {
[contact.company.toLowerCase()]: true
};
const myList = {
[Symbol.iterator]: createIteratorForList
};
function createIteratorForList() { ... }