简体   繁体   中英

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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM