There are many ways to iterate an object in javascript. This post shows few most popular way of iterating an object in javascript

Initialize

Consider following is the object we are going to work with in our example. Objects in javascript does not maintain the insertion order. Insertion order is not maintained while iteration for Objects.


      var person = {};
      person.firstName = "John";
      person["lastName"] = "Taylor";
      person.country = "Canada";
    

Method 1 : Using for…in statement

for...in iterates over enumerable property of an object. It is a good idea to check whether enumerable property belongs to object’s own property or not ? Otherwise for…in loop will iterate over Object’s Prototype property as well.


for(var key in person) {
    if(person.hasOwnProperty(key))
    {
        console.log(key +" - "+ person[key]);
    }
}
// Output
firstName - John
lastName - Taylor
country - Canada
    

Method 2 : Using forEach statement

This method is a combination of Object.keys() and Array.prototype.forEach()


Object.keys(person).forEach(function(key, index) {
    console.log(index + ": "+ key +" - "+ person[key]);
});
// Output
0: firstName - John
1: lastName - Taylor
2: country - Canada
    

Method 3 : Using $.each() in jQuery

$.each() method is provided by jQuery Library.


$.each(person, function(key, value) {
    console.log(key +" - "+ value);
});
// Output
firstName - John
lastName - Taylor
country - Canada
    

Method 4 : Using _.each() in Underscore.js

_.each() method is provided by Underscore.js Library.


_.each(person, function(value, key) {
     console.log(key +" - "+ value);
});
// Output
firstName - John
lastName - Taylor
country - Canada
    

Method 5 : Using _.forIn() in Lodash.js

_.forIn() method is provided by Lodash Library. _.forIn() can iterate over object’s prototype property as well.


_.forIn(person, function(value, key) {
    if(person.hasOwnProperty(key))
    {
        console.log(key +" - "+ value);
    }
});
// Output
firstName - John
lastName - Taylor
country - Canada
    

Method 6 : Using _.forOwn() in Lodash.js

_.forOwn() method is provided by Lodash Library. _.forOwn() can iterate over object’s own property only. It will skip the Object’s inherited properties.


_.forOwn(person, function(value, key) {
    console.log(key +" - "+ value);
});
// Output
firstName - John
lastName - Taylor
country - Canada
    

References

Object in Javascript
Loop through Javascript Object