基本上,您需要遍历模型的属性并将它们的键和值与过滤器的属性进行比较。
self.models = _.filter(self.models, function (model) {
var fits = true; // does this model "fit" the filter?
model = model.toJSON();
_.each(model, function(modelVal, modelKey) {
_.each(filterArr, function(filter) {
if (modelKey === filter.field && modelVal !== filter.filter) {
fits = false
}
}
})
return fits
})
然而,有一点下划线魔法有一个更棘手的方法。我不确定它在性能方面是否更好,但在我看来它肯定看起来更好。
// change a bit the way filter is described:
var filter = {Account: '123', Owner: 'Bob'},
// save an array of filter keys (Account, Owner)
filterKeys = _.keys(filter),
// and an array of its values (123, Bob)
filterVals = _.values(filter)
self.models = _.filter(self.models, function (model) {
// pick a subset of model which has the same keys as filter
var filteredSubset = _.pick(model.attributes, filterKeys),
// pick values of this subset
subsetValues = _.values(filteredSubset)
// this values have to be equal to filter's values
// (use .join() to turn array to string before comparison due to references)
return filteredVals.join() === subsetValues.join()
})
请注意,在后一种情况下,所有模型都必须在过滤器中声明所有键。
如果我是你并且我正在寻找一种最稳健的方法,我会重写第一个示例,但会更改_.each
为标准for
循环并false
在满足第一个“不合适”值时立即返回。