Javascript Associate Arrays / Objects with Dynamic Key Access

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

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 :)


Tags: javascriptarrayassociativeobjectdynamic