JavaScript Object properties iteration


Example

You can access each property that belongs to an object with this loop

for (var property in object) {
    // always check if an object has a property
    if (object.hasOwnProperty(property)) {
        // do stuff
    }
}

You should include the additional check for hasOwnProperty because an object may have properties that are inherited from the object's base class. Not performing this check can raise errors.

5

You can also use Object.keys function which return an Array containing all properties of an object and then you can loop through this array with Array.map or Array.forEach function.

var obj = { 0: 'a', 1: 'b', 2: 'c' };

Object.keys(obj).map(function(key) {
    console.log(key);
}); 
// outputs: 0, 1, 2