Loop through key value pairs from an associative array with Javascript
Posted April 3rd, 2009 in Javascript
This post looks at how to loop through an associate array with Javascript and display the key value pairs from the array. An associative array can contain string based keys instead of zero or one-based numeric keys in a regular array.
If we had the following array defined in Javascript:
var items = {
"foo" : 123456,
"bar" : 789012,
"baz" : 345678,
"bat" : 901234
};
we could loop through the array and display the index and then the value like so:
for(var index in items) {
document.write( index + " : " + items[index] + "<br />");
}
This would display the following:
foo : 123456 bar : 789012 baz : 345678 bat : 901234
Related posts:
- Clear a form with Javascript (Friday, May 22nd 2009)
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- Clearing the default value of text input with Javascript (Tuesday, June 17th 2008)
- Use normal href if Javascript is disabled (Thursday, June 12th 2008)
- Assigning values to associative arrays in Javascript (Sunday, December 30th 2007)
- Testing if a Javascript variable is defined (Tuesday, October 23rd 2007)

Comments
blog comments powered by Disqus