dev.e.loper
dev.e.loper

Reputation: 36044

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

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?

Upvotes: 114

Views: 72005

Answers (2)

Leon Adler
Leon Adler

Reputation: 3331

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

Upvotes: 54

Engineer
Engineer

Reputation: 48793

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 };

Upvotes: 206

Related Questions