the open web, web development, and more

Friday, November 7, 2008

Enumerating Objects in JavaScript

Enumerating through objects is something I only occassionally do in JavaScript, but when it does come up, I always find it a bit unintuitive. Here's some sample code for the future me that is faced with this task again:

var dataObject = {
foo: "bar",
one: "fish",
hello: "world"
};

var key;
for (key in dataObject)
{
document.write("Key: " + key ", Value: " + dataObject[key]);
document.write("\n");
}

This code will produce the following lines:
Key: foo, Value: bar
Key: one, Value: fish
Key: hello, Value: world

No comments:

Post a Comment