AnApprentice AnApprentice - 1 year ago 65
jQuery Question

How to use Underscore.js filter with an object?

I have an object like so:

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


How can I use the underscore
to return back only the items where selected === true?

I've never had the need to go down to layers with
. Something like

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

Thank you

rjz rjz
Answer Source

If you want to pull all array elements from any e-mail address where selected is true, you can iterate like so:

var selected = [];

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

If you only want to pull the arrays where all elements are selected, you might instead do something like this:

var stuff = _.filter(me.collections, function(item) {
    return _.all(item, function (jtem) { 
        jtem.selected === true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download