How to iterate over an object

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;

// Initializing the object "eat"

var eat ={

'fruit':'durian',

'vegetable':'broccoli',

'sweets':'chocolate'

},

key;

for(key in eat){

if(eat.hasOwnProperty(key)){

console.log(eat[key]);

}

}

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.