Skip to main content Accessibility Feedback

Looping through objects with ES6

Last week, we looked at how to loop through arrays and NodeLists with ES6, which provides handy forEach() methods.

Because JavaScript is weird, there’s no forEach() method for objects.

Traditionally, you’d need to use a for...in loop.

var lunch = {
    sandwich: 'turkey',
    chips: 'Cape Cod',
    snack: 'Cookies',
    drink: 'Pepsi',
    calories: 325,
    picnic: true
};

for (var key in lunch) {
    if (lunch.hasOwnProperty(key)) {
        console.log(key); // key (ex. sandwich)
        console.log(lunch[key]); // value (ex. turkey)
    }
}

Adding an Object.forEach() method #

That said, we can add our own Object.forEach() method by extending the object prototype.

You normally extend prototypes by doing something like this:

Object.prototype.forEach = function () {
    // Our code goes here...
}

That works great for things like arrays and elements, but can break a whole bunch of things if you try to do it with objects.

Instead, we need to use the defineProperties() method.

if (!Object.prototype.forEach) {
    Object.defineProperties(Object.prototype, {
        'forEach': {
            value: function (callback) {
                if (this == null) {
                    throw new TypeError('Not an object');
                }
                var obj = this;
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        callback.call(obj, obj[key], key, obj);
                    }
                }
            },
            writable: true
        }
    });
}

Now you can loop through objects just like you would arrays and NodeLists.

var lunch = {
    sandwich: 'turkey',
    chips: 'Cape Cod',
    snack: 'Cookies',
    drink: 'Pepsi',
    calories: 325,
    picnic: true
};

lunch.forEach(function (item, key) {
    console.log(key); // the key (ex. sandwich)
    console.log(item); // the item (ex. turkey)
});

This works all the way back to IE9, and if you use polyfill.io, you can extend that even further back to IE7.


🔥 Hot off the press! I just launched a new pocket guide. Learn how to build interactive web apps with vanilla JavaScript.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips