How to iterate over an object

JavaScript polyfill, by , Friday, March 7th, 2014

Iterating over an object is as easy as iterating over an array, but instead of using the for-loop, you should use the for-in loop;

  1. // Initializing the object "eat"
  2. var eat = {
  3. 'fruit' : 'durian',
  4. 'vegetable' : 'broccoli',
  5. 'sweets' : 'chocolate'
  6. },
  7. key;
  8.  
  9. for (key in eat) {
  10. if (eat.hasOwnProperty(key)) {
  11. console.log(eat[key]);
  12. }
  13. }

This for-in loop will iterate over all the properties that contains including what it might have inherited from another object through the prototype chain. This is usually not what you want, so to only get the properties of this object, excluding what it might have inherited, we put in the if statement with the condition eat.hasOwnProperty(key). In case, that you want to loop over everything in this object, including what it might have inherited, you just need to leave out the if statement.