The most elegant way to return a value from jQuery $ .each?

I was wondering if there is a more elegant way to return the value from the function I inserted below: "getImageURLforPOICategory".

As you can see, I used the "every" jQuery function to iterate over an array of objects, when I find a matching value, I want to return the result from the "each" loop, and then directly from the function that contains each loop.

I used a local variable to "cache" it, and then I return it. I'm not quite sure what is the best approach? Is there a way to return a value directly from within 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,

Greetings

Duncan

+3
source share
2 answers

, .each().

return false;, , , , , .

$.each(), for, :

return Tracker.pointofinterestcategories[ i ].imageurl
+2

for.

Tracker.getImageURLforPOICategory = function (POICategoryID) {
    return $.grep(Tracker.pointofinterestcategories, function (item) {
        return item.id === POICategoryID;
    })[0].imageurl;
}
0

Source: https://habr.com/ru/post/1784320/


All Articles