Search code examples
javascriptprototype

How might I be able to use Array.prototype.forEach on an object?


I'm just trying to make a little framework for learning purposes, and I want to be able to use Array.prototype.forEach on objects, this is what I have right now,

var data = { test: 'test' };

Array.prototype.forEach(data, function(key value) {
    console.log(key);
});

But I get an error, I'm sure you guys can see why, but I can not :) So any help would be great thanks :)


Solution

  • Objects are not arrays, and don't have access to the array prototype. You can just loop over the properties.

    for(var key in data){
          console.log(key) //or data[key] if you want the values
       }
    

    with regards to the jQuery comment below, it appears they use loops internally for their "each" function. From the source:

    // args is for internal usage only
    each: function( obj, callback, args ) {
        var value,
            i = 0,
            length = obj.length,
            isArray = isArraylike( obj );
    
        if ( args ) {
            if ( isArray ) {
                for ( ; i < length; i++ ) {
                    value = callback.apply( obj[ i ], args );
    
                    if ( value === false ) {
                        break;
                    }
                }
            } else {
                for ( i in obj ) {
                    value = callback.apply( obj[ i ], args );
    
                    if ( value === false ) {
                        break;
                    }
                }
            }
    
        // A special, fast, case for the most common use of each
        } else {
            if ( isArray ) {
                for ( ; i < length; i++ ) {
                    value = callback.call( obj[ i ], i, obj[ i ] );
    
                    if ( value === false ) {
                        break;
                    }
                }
            } else {
                for ( i in obj ) {
                    value = callback.call( obj[ i ], i, obj[ i ] );
    
                    if ( value === false ) {
                        break;
                    }
                }
            }
        }
    
        return obj;
    },