Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key as variable when accessing javascript dictionary

i am trying to store css values for transformations of multiple divs in a dictionary to access them when the div is clicked (the div id being the key of the dict).

my dictionary:

css_dict = {
    'keyA' : ['10px, 15px', '20px', '10px'],
    'keyB' : ['20px, 30px', '10px', '20px'],
    'keyA' : ['30px, 55px', '25px', '30px'],
}

i need to access it like this (variable instead of the key):

css_dict.var[0]

jsFiddle of what im trying to do: http://jsfiddle.net/tKFka/25/

i cant figure out or find the right syntax for this to work...

like image 849
user1952949 Avatar asked Jan 06 '13 15:01

user1952949


People also ask

How do you access a dictionary in JavaScript?

A simple JavaScript “for” loop can be used to iterate through your new dictionary. By using the “for(var key in dict)” method of iterating on the object you are able to easily access all the key/value pairs in contains.

How do you get the value of a variable as a key in an object?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!

Can a JavaScript object key Be a string?

JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).


1 Answers

Use [] instead of dot.

var var1 = 'keyA';
css_dict[var1][0];
like image 200
Marius Balčytis Avatar answered Oct 04 '22 03:10

Marius Balčytis