Filter a collection by multiple attributes

382 views Asked by At

I'm using underscore's filter method to retrieve the models I need within a collection. Here's my code so far:

search = {'name':'Jordan', 'country':'Brazil'};

var people = this.filter(function(person){

    return person.get('name') == search['name']
    && person.get('country') == search['country'];
});

My problem is, I don't know how many key/value pairs I will receive in the search object. A simple solution would be something like this:

search = {'name':'Jordan', 'country':'Brazil'};

var people = this.filter(function(person){

    for(var key in search)
    {
        if(search.hasOwnProperty(key)) return person.get(key) == search[key];
    }
});

But of course it does not work. What can I do?

Edit:

The keys I get in the search object are not necessarily attributes of the models I am filtering. I might receive search = {'name':'Jordan', 'country':'Brazil', 'parentName': 'Steve'};

So one of the filter conditions would be Parents.byID(person.get('parentID')).get('name') == search['parentName'];

1

There are 1 answers

0
CrackerKraken On BEST ANSWER

Worked it out:

var select = true;

for(var key in search)
{
    if(search.hasOwnProperty(key))
    {
        select = (person.get(key) == search[key]) ? true : false ;
    }

    if(select == false) break;
}

return select;