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:

JAVASCRIPT:
  1. var assocArrayObject = {"key1":"value1", "key2":"value2"};
  2.  
  3. 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

JAVASCRIPT:
  1. var dynamicKey = "key1";
  2.  
  3. //doesnt work
  4. alert(assocArrayObject.dynamicKey);
  5.  
  6. //does work
  7. alert(assocArrayObject[dynamicKey]);

easy when you know how, took me a while to clear this one up :)

More Reading:

2 Comments

Me
November 1st, 2011

Yes but how do you put dynamic key / value pairs INTO the assoc array?

 

admin
November 2nd, 2011

assocArrayObject.key3 = "value3";
or
assocArrayObject['key3'] = "value3";

This can then be accessed using either assocArrayObject.key3 or assocArrayObject['key3']

 

 

Leave a Reply