Udders
Udders

Reputation: 6976

Filter/Search a collection based on 2 attributes

I am trying to search a collection using 2 search parameters. Currently I am only managing to search via 1 search paramater, here is my working single parameter search.

search: function(filterValue) {
    var filterValue = filterValue.toLowerCase();
    var matcher = new RegExp(filterValue);
    var found_models = this.filter(function(model) {
        return matcher.test(model.get('name').toLowerCase());
    });

    return found_models;
},

is there way to also search another attribute other than the name, I thought maybe something like this,

search: function(filterValue) {
        var filterValue = filterValue.toLowerCase();
        var matcher = new RegExp(filterValue);
        var found_models = this.filter(function(model) {
            return matcher.test(model.get('name').toLowerCase());
        });
        var found_models = this.filter(function(model) {
            return matcher.test(model.get('clients').get('name').toLowerCase());
        });

        return found_models;
    },

but these to just overwrite any results that match the name parameter.

Upvotes: 0

Views: 56

Answers (2)

Laurens Kling
Laurens Kling

Reputation: 2261

The trick is in the returning of the filter. If you return true that model is added to the output. This means you can do any kind of matching within the filter function, even double matching!

So code would be something like:

var found_models = this.filter(function(model) {
    return matcher.test(model.get('name').toLowerCase()) && matcher.test(model.get('clients').get('name').toLowerCase());
});

This gives true && true, which will make true to your return.

Upvotes: 1

Lesha Ogonkov
Lesha Ogonkov

Reputation: 1238

Something like where method?

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

alert(musketeers.length);

Upvotes: 0

Related Questions