Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Underscore.js filter with an object?

I have an object like so:

> Object
  > [email protected]: Array[100]
  > [email protected]: Array[4]
    > 0
       id : 132
       selected : true
    > 1
       id : 51
       selected : false

etc..

How can I use the underscore _.filter() to return back only the items where selected === true?

I've never had the need to go down to layers with _.filter(). Something like

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

Thank you

like image 997
AnApprentice Avatar asked Jul 28 '12 02:07

AnApprentice


1 Answers

@Dexygen was right to utilize _.pick but a cleaner solution is possible because the function also accepts a predicate

Return a copy of the object, filtered to only have values for the allowed keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

(highlight is mine)

Here's a real life example I've used in a project

_.pick({red: false, yellow: true, green: true}, function(value, key, object) {
    return value === true;
});
// {yellow: true, green: true}
like image 194
svarog Avatar answered Nov 15 '22 23:11

svarog