Javascript - Objects as Associative Arrays


In Javascript, every object is also an associative array of keys and values. Each 'variable' or 'attributes' of the object is a key value pair, where the name of the variable is the 'key' and the value of the variable is the 'value' of the kv pair. This means that you can iterate through an object's 'attributes'.

Your own object:
function assoc1()
{
    var m = new Object();
    m["has_cpu"] ="Y";
    m.has_memory ="N";
    for( var key in m )
    {
        alert( key+":"+m[key] );
    }
}

An existing html element:
function assoc2()
{
    var e = document.getElementById('div_id');
    for( var key in e )
    {
        alert( key+":"+e[key] );
    }
}


This is especially useful for debugging, and building cross-browser web applications, because different browsers pre-define different attributes and methods in their javascript implementations.

The body element:
function assoc3()
{
    var b = document.body;
    for( var key in b )
    {
        console.log( key+":"+b[key] );
    }
}

The console.log function is defined in Firebug, and an excellent debugging tool. It is important to use something like firebug when debugging instead of just 'alert' boxes, because sometimes you would have to click [OK] on 90 alert boxes, like if you output predefined objects like 'body' as associative arrays.

code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)