Home / Loop through key value pairs from an associative array with Javascript

Loop through key value pairs from an associative array with 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