JavaScript Tip: Iterating over an Object

Iterating over an object isn’t as simple as looping over an array. With an array, you simply increment an index value and use that to step through the array. With objects, there is no index value.

Objects are collections of key/value pairs, so you need to step through them differently:


In this example, we use a for … in loop. We give it a variable (in this case, key) that will be used to hold the key as it steps through the object, and an object to step over (in this case, data).

For each key/value pair inside data, the loop will assign the key to our variable named key. Inside the body of the loop, we can use the key to plug into our object to access its associated value: data[key]. That’s the equivalent of writing data[“firstName”], and on a subsequent pass, data[“lastName”], and so on.

There is one catch, though. Since objects inherit from objects, the loop may start returning key/value pairs from further up the prototype chain. To prevent this, we need to add something to our loop:

The hasOwnProperty method makes sure that the key we’re using belongs to the  object in question and not from further up the prototype chain. If it returns true,  we can proceed with our operation. Otherwise, we ignore it.

Leave a Reply

Your email address will not be published. Required fields are marked *