tiagomac
tiagomac

Reputation: 2995

How to return from a $.each operation? (jQuery)

Example:

var t = $.each(templos_cache, function(f,g){
 $.each(g.requer, function(h,j){
  if (parseFloat(g.id) == id){
   alert(j.nome); // OK, return 'afrodite'.
   return j.nome; // wrong, return [Object object].
  }
  });
  return '';
 });

Looking at the code we can see the problem... i can do a set in a variable out of scope but i think that can exist some more elegant way to do this.

Upvotes: 9

Views: 1229

Answers (4)

user578895
user578895

Reputation:

You may be looking for $.map instead:

var x = [1, 2, 3, 4, 5];
var y = $(x).map(function(i, n){
    return n < 4 ? n+1 : undefined;
});
// y == [2, 3, 4]

If you only return one value, y will be [val] and you can always access it with y[0]

Upvotes: 1

Patricia
Patricia

Reputation: 7802

in THEORY something like this should do what you want. it should loop through templos_cache, and inside loop through g.requer until id matches g.id. in that case it will set returnValue, and break out of the inside $.each loop. and in the outside loop it checks if returnValue has been set, if so, breaks out of the loop.

I haven't actually tested this. but it seems solid

var returnValue = ''; 

$.each(templos_cache, function(f,g){
    $.each(g.requer, function(h,j){
        if (parseFloat(g.id) == id){
             returnValue = j.nome;
             return false;
        }
     });
     if(returnValue != ''){
         return false;
     }

});

var t = returnValue;

Upvotes: 1

Jack Murdoch
Jack Murdoch

Reputation: 2894

To break out of $.each(), simply return false; from the callback function. As quoted from the jQuery documentation:

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.

Edit:

Upon realising you may want to return a value, you could simply pass an object to the callback function as this is passed by reference. See How to append a string value during assignment in Javascript? - this isn't at all any more elegant though, so I'd stick with just setting a variable outside of $.each as colinmarc said.

Upvotes: 12

colinmarc
colinmarc

Reputation: 2471

Off the top of my head, setting a variable seems like the most elegant way to do it, like you mentioned:

var foo = '';
$.each(some_list, function(i, e){
   ...
   if(something) foo = 'stuff';
});

Upvotes: 2

Related Questions