Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 921
dev.e.loper Avatar asked May 17 '12 17:05

dev.e.loper


People also ask

How do you set an object key to a variable?

You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);

How do you define a Dictionary in JavaScript?

Creating a JavaScript Dictionary A dictionary can be created using two methods. The Object Literal method or by using the new keyword. However, we focus on the former. This is because it is very likely that you have used dictionaries before and this method follows a familiar syntax.

What are dictionaries in JavaScript called?

While JavaScript doesn't natively include a type called “Dictionary”, it does contain a very flexible type called “Object”. The JavaScript “Object” type is very versatile since JavaScript is a dynamically typed language.


1 Answers

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 }; 
like image 127
Engineer Avatar answered Oct 04 '22 23:10

Engineer