rkap
rkap

Reputation: 3

js dictionary with key stored in variable

I have dictionary and a variable that stores the key. How do I access "value1"? Can myKey be evaluated before the dictionary lookup?

var dic = { "key1" : "value1",
            "key2" : "value2",
            "key3" : "value3"};

var myKey = "key1";

console.log(dic.myKey);

Upvotes: 0

Views: 2399

Answers (2)

StoneMan
StoneMan

Reputation: 423

If you use the dot notation for access values, whatever you put becomes the key, so dic.myKey searches for the key "myKey".

To avoid this, you'll need to use the bracket notation. To find something using brackets, you'll have to use dic[keyVariable]. So in your case, you can access value1 by using dic[myKey].

Upvotes: 0

Musa
Musa

Reputation: 97672

You'll have to use the square bracket notation []

var dic = { "key1" : "value1",
            "key2" : "value2",
            "key3" : "value3"};

var myKey = "key1";

console.log(dic[myKey]);

Upvotes: 2

Related Questions