Question

Is there a way to jump the current iteration inside Object.each() if a condition is met?

I could use:

Object.each(myObject, function(item, key){
    if(key != 'someString'){
        //do everything
    }
});

but i would like something like

Object.each(myObject, function(item, key){
    if(key == 'someString') continue;
});
Était-ce utile?

La solution

You can add the same stuff for objects as we have for Arrays.

P.S. I hope btw your question is about break, right? not continue?

Because to continue all you need to do is return early from the callback fn of your Object.each...

Object.each(myObject, function(item, key){
    if(key == 'someString') return;
    // code here will run only if key is somethingelse.
});

Anyway, implementing Object.every and Object.some (not on the proto, just hosted on Object)

(function(){
    var hasOwnProperty = Object.hasOwnProperty;
    Object.extend({
        some: function(obj, cb, bind){
            for (var k in obj){
                if (hasOwnProperty.call(obj, k)){
                    if (cb.call(bind, obj[k], k, obj)) break;
                }
            }
        },
        every: function(obj, cb, bind){
            for (var k in obj){
                if (hasOwnProperty.call(obj, k)){
                    if (!cb.call(bind, obj[k], k, obj)) break;
                }
            }
        }
    });
}());

Here is some use:

var foo = {
    one: 1,
    two: 2,
    bar: 'haha',
    three: 3
};

// loop keys until the key is bar then stop.
Object.some(foo, function(value, key){
    console.log(key, value);
    return key === 'bar';
});

// loop keys until a non-number is encountered, then stop
Object.every(foo, function(value, key){
    console.log(key, value);
    return typeof value === 'number';
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top