Home / Iterate through an associative array the jQuery way

Iterate through an associative array the jQuery way

A few months ago I posted how to loop through key value pairs from an associative array with Javascript. I do a lot of work with jQuery these days (and am about to start working with MooTools on a new project, so am bound to start posting about MooTools shortly 🙂 so in this post look at how to do the same but using jQuery’s each function.

Loop through key value pairs with jQuery

The example below uses the associative array defined as follows:

var data = {
    val1 : 'text1',
    val2 : 'text2',
    val3 : 'text3'
};

And this code loops through the above array, showing the key/index (e.g. "val1") and the value (e.g. "text1") in an alert dialog:

$.each(data, function(key, value) {
    alert( "The key is '" + key + "' and the value is '" + value + "'" );
});

Obviously how you choose to work with the data depends on the situation; the above example shows the information in an alert dialog because that’s what the working example below does.

Working Example

By clicking the button below the example code above is executed and you will see three alert dialogs with each of the key-value pairs.

Note that as with all my Javascript examples, if you are reading this in a feed reader you will need to click through to view this in a web browser for it to work.