Our blog
Javascript Associate Arrays / Objects with Dynamic Key Access
If you are trying to use associative arrays in Javascript, the first thing is to not use the Array type and instead just use objects.
The weird and wonderful thing is that if you create your array as an object, you can still use the array style square brackets to access object properties.
So for example take this:
-
var assocArrayObject = {"key1":"value1", "key2":"value2"};
-
-
alert(assocArrayObject["key1");
You can also access object properties by using a dynamic key this way as well, but not via the normal method, for example
-
var dynamicKey = "key1";
-
-
//doesnt work
-
alert(assocArrayObject.dynamicKey);
-
-
//does work
-
alert(assocArrayObject[dynamicKey]);
easy when you know how, took me a while to clear this one up
More Reading:
2 Comments
|
Yes but how do you put dynamic key / value pairs INTO the assoc array? |
|
assocArrayObject.key3 = "value3"; This can then be accessed using either assocArrayObject.key3 or assocArrayObject['key3'] |
RSS Feed
Me
November 1st, 2011