我想根据某些条件从列表中过滤掉某些对象:
var list = [
{ mode: 1, type: 'foo' },
{ mode: 2, type: 'foo' },
{ mode: 3, type: 'foo' }, // remove this item
{ mode: 1, type: 'bar' },
{ mode: 2, type: 'bar' },
{ mode: 3, type: 'bar' }
];
var blah = $.grep(list, function(x){
if(x.type === 'foo')
return x.mode !== 3;
else
return true;
});
console.log('result 1:', blah);
http://jsfiddle.net/65LeJ/
正如预期的那样工作。
我的问题是我有一个过滤器,该过滤器从服务器作为JSON发送:
var blah = list;
var filter = [
{ propertyName: 'mode', value: 3 },
{ propertyName: 'type', value: 'foo' }
];
$.each(filter, function(k, filterRow){
blah = $.grep(blah, function(listItem){
return listItem[filterRow.propertyName] === filterRow.value;
});
});
http://jsfiddle.net/65LeJ/1/
显然,这会过滤掉太多内容,但这只是为了让您对它的工作方式有所了解。
我想知道的是您对过滤器应如何过滤出与我的第一个示例相同数量的行的建议。
不,我不想传递表达式并使用
eval()
。如果有任何不清楚的地方,请告诉我。
最佳答案
使用[].filter
和[].every
会更好。
这是我的解决方案:
var list = [
{ mode: 1, type: 'foo' },
{ mode: 2, type: 'foo' },
{ mode: 3, type: 'foo' }, // remove this item
{ mode: 1, type: 'bar' },
{ mode: 2, type: 'bar' },
{ mode: 3, type: 'bar' }
];
var blah = list;
var filter = [{ propertyName: 'mode', value: 3 }, { propertyName: 'type', value: 'foo' }];
var filtered = list.filter(function(listItem) {
return !filter.every(function(filterItem) {
return listItem[filterItem.propertyName] === filterItem.value;
});
});
console.log(filtered);
http://jsfiddle.net/Dogbert/65LeJ/2/
关于javascript - 根据自定义过滤器使用$ .grep()过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17444877/