javascript

How to iterate over an object in Javascript (ES5)

Below is an example of how to iterate over an object using vanilla JavaScript. You will want to call the hasOwnProperty method in order to avoid iterating over the objects prototype.

var obj = {
    "key1" : "val1",
    "key2" : "val2",
    "key3" : "val3"
}

for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
        console.log(property);
        console.log(obj[property]);
    }
}

Alternatively, if you are using a library called underscore.js, you can use the _.each method. This method passes each iteration through a callback function and offers a bit of syntactic sugar.

var obj = {
    "key1" : "val1",
    "key2" : "val2",
    "key3" : "val3"
}

_.each(obj, function(val, key) {
    console.log(key);
    console.log(val);
});

JQuery also offers its own $.each method which is very similar to the one used in underscore.

var obj = {
    "key1" : "val1",
    "key2" : "val2",
    "key3" : "val3"
}

$.each(obj, function(key, val) {
    console.log(key);
    console.log(val);
});

more JavaScript posts