1

I am trying to return an object based on some conditions i.e if some condition is satisfied I want to break the loop and return the object back to the called function.

below is my code.

function someFun(that,filterID,columnSelctedID) {
    $.each(that.filters,function(i,filter) {
        if(filter.id==filterID) {
            $.each(filter.filters,function(j,column) {
                if(column.id==$('#' + columnSelctedID + ' .rule-filter-container-column select').val()) {
                    return column;
                }
            });
        }
    });
}
lshettyl
  • 8,166
  • 4
  • 25
  • 31
Vallabha
  • 1,591
  • 3
  • 13
  • 21
  • Are you sure that the if ever runs? – nicael Mar 27 '15 at 18:14
  • it would be really helpfull if you can reproduce the issue in a fiddle. – Lal Mar 27 '15 at 18:14
  • if(filter.id==filterID), where is filter.id you will get value? – Wahyu Kodar Mar 27 '15 at 18:15
  • @nicael yes I can see that the control is coming at line `return column` and proceeding with the loop. – Vallabha Mar 27 '15 at 18:16
  • @WahyuKodar in the $.each u can a find object with name filter which has id property – Vallabha Mar 27 '15 at 18:18
  • Possible duplicate of [http://stackoverflow.com/questions/8224375/jquery-each-stop-loop-and-return-object](http://stackoverflow.com/questions/8224375/jquery-each-stop-loop-and-return-object) – lshettyl Mar 27 '15 at 18:19
  • $.each will iterate over each item in the collection whether you return some value or not. What you need is something like Underscore's 'find' method. I don't think jquery has an equivalent to that. If you do not want to use Underscore, then use a vanilla 'for' loop – Manokaran K Mar 27 '15 at 18:23
  • FYI, this may be a case where it's a lot simpler to just use a regular `for` loop rather than `$.each()` because then you can just `return column` from anywhere. – jfriend00 Mar 28 '15 at 16:39

1 Answers1

0

You must use return false to breack .each loop. You can use an external variable to assign selected value. Something like this may do the trick

function someFun(that,filterID,columnSelctedID) {
    var col; // this is used to hold selected column
    $.each(that.filters,function(i,filter) {
        if(filter.id==filterID) {
            $.each(filter.filters,function(j,column) {
                if(column.id==$('#' + columnSelctedID + ' .rule-filter-container-column select').val()) {
                    col = column;
                    return false;
                }
            });
        }
    });
    return col;
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • but I want to return the column to the called function, of course I can use a global variable but I am not interested to do so – Vallabha Mar 27 '15 at 18:21
  • @user1655222: just added return col to the function. You probably want to add some condition on outer each to make it break too. Maybe checking when changes its default value? – Claudio Redi Mar 27 '15 at 18:31