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?
You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);
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.
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.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With