How to use Underscore.js filter with an object?

I have an object like this:

> Object > Rett@site.com : Array[100] > pel4@gmail.com : Array[4] > 0 id : 132 selected : true > 1 id : 51 selected : false 

etc..

How can I use the underscore character _.filter() to return only those elements where === true is selected?

I never had to go down to layers with _.filter() . Something like

 var stuff = _.filter(me.collections, function(item) { return item[0].selected === true; }); 

thanks

+7
source share
4 answers

If you want to pull all the elements of the array from any email address where selected is true , you can do the same:

 var selected = []; for (email in emailLists) { selected.concat(_.filter(emailLists[email], function (item) { return item.selected === true; })); } 

If you only want to output arrays where all the elements are selected , you can do something like this:

 var stuff = _.filter(me.collections, function(item) { return _.all(item, function (jtem) { jtem.selected === true; }); }); 
+8
source

The underscore filter method will work on the object used as a hash or dictionary, but it will return an array of enumerated values ​​of the object and cross out the keys. I need a function to filter a hash by its values, which would preserve keys, and write this in Coffeescript:

 hash_filter: (hash, test_function) -> keys = Object.keys hash filtered = {} for key in keys filtered[key] = hash[key] if test_function hash[key] filtered 

If you are not using Coffeescript, here the compiled result in Javascript has cleared a bit:

 hash_filter = function(hash, test_function) { var filtered, key, keys, i; keys = Object.keys(hash); filtered = {}; for (i = 0; i < keys.length; i++) { key = keys[i]; if (test_function(hash[key])) { filtered[key] = hash[key]; } } return filtered; } hash = {a: 1, b: 2, c: 3}; console.log((hash_filter(hash, function(item){return item > 1;}))); // Object {b=2, c=3} 

TL; DR: Object.keys () is great!

+4
source

I have an object called allFilterValues ​​containing the following:

 {"originDivision":"GFC","originSubdivision":"","destinationDivision":"","destinationSubdivision":""} 

This is ugly, but you asked for an underline-based way to filter the object. This is how I returned only filter elements that had non-fake values; you can switch the return statement to everything you need:

  var nonEmptyFilters = _.pick.apply({}, [allFilterValues].concat(_.filter(_.keys(allFilterValues), function(key) { return allFilterValues[key]; }))); 

Output (JSON / stringified):

 {"originDivision":"GFC"} 
+1
source

Maybe you need the easiest way

 _.filter(me.collections, { selected: true}) 
-one
source

All Articles