Key for javascript dictionary is not stored as value but as variable name

Javascript

Javascript Problem Overview


I'm trying to create a dictionary object like so

var obj = { varName : varValue };

What I'm expecting is if varName='foo', the obj should be {'foo', 'some value' } however what I see is {varName, 'some value'} the value of variable is not being used but a variable name as a key. How do I make it so that varible value is used as key?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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() { ... }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondev.e.loperView Question on Stackoverflow
Solution 1 - JavascriptEngineerView Answer on Stackoverflow
Solution 2 - JavascriptLeon AdlerView Answer on Stackoverflow