1

I have a $.each method that searches through a JSON to find the variable and I am using this code:

$.each(heroes_json.heroes, function(key, val){
    if(val.id == hero){
        hero = val.localized_name;
        console.log("Hero name is "+hero);
        return;
    }
    else{
        console.log("Wrong hero, skipping...");   
    }        
});

The problem however is that I get this in my console log:

enter image description here

So from what I understand, the $.each method is, as described, going over every object in the JSON. How can it be made so that when the desired variable (in this case hero) is found, that it stops the each method? I am assuming that this is desired for performance purposes?

k4kuz0
  • 1,045
  • 1
  • 10
  • 24
  • A similar question here http://stackoverflow.com/questions/1784780/how-to-break-out-of-jquerys-each-loop – Tasos K. Feb 13 '14 at 08:55
  • @codingstill Ah sorry. I didn't find it because I searched things like 'stop each method'. I get confused with all the names: method function loop break out etc. – k4kuz0 Feb 13 '14 at 08:56

3 Answers3

1

You need to return false from the each handler method to stop further processing of the loop

$.each(heroes_json.heroes, function (key, val) {
    if (val.id == hero) {
        hero = val.localized_name;
        console.log("Hero name is " + hero);
        //return false to stop the loop
        return false;
    } else {
        console.log("Wrong hero, skipping...");
    }
});

jQuery.each()

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You must return false to break out of each():

if (val.id == hero) {
    hero = val.localized_name;
    console.log("Hero name is " + hero);
    return false;
}

Plain return; is equivalent to returning undefined, and the each() loop will continue in that case.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
0

You need to return false in order for it to break the loop. So in your instance you will need:

console.log("Hero name is " + hero);
return false; //this is instead of using return;
TheOneWhoPrograms
  • 629
  • 1
  • 8
  • 19