Javascript associative array (objects)

Javascript does not have associative arrays, only key numbered arrays. But it is posible to use javascript objects and let them behave as associative arrays, example:


//-- Create object<script>
var myObject = { 'level1': {'level1-sub1' : 'value 1 1', 'level1-sub2' : 'value 1 2', 'level1-sub3' : 'value 1 3'},
'level12' : {'level2-sub1' : 'value 2 1', 'level2-sub2' : 'value 2 2', 'level2-sub3' : 'value 2 3'},
'level13' : {'level3-sub1' : 'value 3 1', 'level3-sub2' : 'value 3 2', 'level3-sub3' : 'value 3 3'}};

//-- Loop object
function loopObj(myObject)
{
for (i in myObject) {
if (typeof myObject[i] === 'object') {
loopObj(myObject[i]);
} else {
alert(myObject[i]);
}
}
}

loopObj(myObject);
</script>

Javascript objects can be read in two ways, myObject.myKey or myObject[‘myKey’]. The second ways has to be used if you want to loop throw all keys.

Read this blog post for more info: http://www.quirksmode.org/js/associative.html

Annonser

Kommentera

Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut / Ändra )

Twitter-bild

Du kommenterar med ditt Twitter-konto. Logga ut / Ändra )

Facebook-foto

Du kommenterar med ditt Facebook-konto. Logga ut / Ändra )

Google+ photo

Du kommenterar med ditt Google+-konto. Logga ut / Ändra )

Ansluter till %s