Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to return value from within JQuery $.each?

I was wondering if there a more elegant way of returning a value from the function I've pasted below : "getImageURLforPOICategory".

As you can see I've used JQuery's "each" function to iterate through an array of objects, when I find the matching value I want to return a result out of the "each" loop and then right out of the function that contains the each loop.

I've used a local variable to "cache" it and then I'm returning that. I'm not entirely sure if this is the best approach? Is there a way of returning the value directly from within the each loop?

Tracker.getImageURLforPOICategory = function (POICategoryID) {
 var url;
 $.each(Tracker.pointofinterestcategories, function () {
  if (this.id === POICategoryID) {
   url = this.imageurl;
   return;
  }
 }
 );
 return url;
};

Thanks for reading,

Cheers,

Duncan

like image 757
Duncan_m Avatar asked Jan 25 '26 09:01

Duncan_m


1 Answers

No, you can't return a value from the .each().

If you do a return false; it will stop the loop so it isn't running longer than it needs to, but you'll need to use a variable as you're doing now.

If you don't use $.each(), but instead use a for loop, you'll be able to just:

return Tracker.pointofinterestcategories[ i ].imageurl
like image 73
user113716 Avatar answered Jan 27 '26 23:01

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!