Removing sets for loops from Javascript code

I am writing some code for a web application that regularly needs to filter an array of javascript objects to return a subset of objects. I find that throughout my code I get numerous for loops. I plan to write a prototype function that can return a filtered subset using a passed function similar to a C # LINQ lambda or Scala filter, but I cannot help but think that this has already been done, either in the main language or in an external library, and I invent wheel.

Is there a preferred way to functionally return a filtered subset of Json objects without focusing on my code. The syntax is not relevant, but the design and concept are similar:

 var filteredObj = obj.filter(function() {... filter function ...}); 
+4
source share
4 answers

Have you looked underscore ?

There are many functional programming tools, including map , filter and reduce

There is a subtle utility in this library that makes JavaScript a little bigger, uh, gem, functional.

+3
source

jQuery has a grep() function that can filter an array of objects.

Things get ugly when you need recursion or when you want to filter attributes of each object, because then the filter function may depend on the context.

+2
source

This is actually a very good idea. You could do something like this

 Array.prototype.Where = function(filterFn){ var i, results = []; for (i = 0; i < this.length; ++i){ if (filterFn.call(this, this[i])){ results.push(this[i]); } } return results; }; 

Then it would make sure that every array in your json would have a Where method, which you can use for filtering (just like linq).

0
source

If you target a browser audience that supports JavaScript 1.6 and above, map and filter are part of the main language and do not need library support. Interestingly, JavaScript 1.8 also introduces an array method into the main language.

0
source

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


All Articles