Wells
Wells

Reputation: 10969

jQuery: breaking out of nested $.each loop

I am looping through rows in a list w/ $.each, and on each row applying a set of filters with $.each. I'd like to skip rows that do not match. It kinda looks like this:

$.each(data, function(i, row) {
    count      = parseInt(row['n']);
    year       = row['year'];

    if (options.filters) {
        $.each(options.filters, function(filter, filtervalue) {
            if (row[filter] != filtervalue) return true;
        });
    }

    // Will only get here if all filters have passed
}

How can I get the nested $.each loop to skip the row if filtervalue does not match a given filter?

Upvotes: 1

Views: 2057

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

You want to skip a row if there is not at least one filter that filtervalue does not match, right? Then don't skip a row iff the filtervalue matches at least one filter.

$.each(data, function(i, row) {
    count      = parseInt(row['n']);
    year       = row['year'];


    // if there are no filters, don't skip the row (right? ;-)
    var skipRow = !!options.filters;

    if (options.filters) {
        $.each(options.filters, function(filter, filtervalue) {
            if (row[filter] == filtervalue) {
                skipRow = false;
            }
        });
    }

    if (skipRow) return true;
}

Upvotes: 1

Related Questions