javascript 是否可以使用下划线按多个值过滤数组值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19476067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to filter array values by multiple values by using underscore?
提问by Erik
I have the following array of values:
我有以下值数组:
[
{
id: 1,
field: 'map'
},
{
id: 2,
field: 'dog'
},
{
id: 3,
field: 'map'
}
]
I need to find out elements with field equals dog
and map
. I know I could use the _.filter
method and pass an iterator function, but what I want to know is whether or not there's a better solution to this issue where I could pass search field and possible values. Could someone provide a better way of doing so?
我需要找出字段等于dog
和的元素map
。我知道我可以使用该_.filter
方法并传递迭代器函数,但我想知道是否有更好的解决方案可以解决这个问题,我可以传递搜索字段和可能的值。有人可以提供更好的方法吗?
EDIT::
编辑::
I could use the following approach:
我可以使用以下方法:
_.where(array, {field: 'dog'})
But here I may check only one clause
但在这里我只能检查一个子句
回答by vkurchatkin
_.filter(data, function(item){ return item.field === 'map' || item.field === 'dog'; })
If you want to create a function which accepts field
and values
it can look like this:
如果你想创建,它接受一个函数field
和values
它可以是这样的:
function filter(data, field, values) {
_.filter(data, function(item){ return _.contains(values, item[field]); })
}
回答by Andreas
Just pass your filter criteria as the third parameter of _.filter(list, predicate, [context])
which is then set as the context
(this
) of the iterator:
只需将过滤条件作为第三个参数传递_.filter(list, predicate, [context])
,然后将其设置为迭代器的context
( this
):
var data = [
{ id: 1, field: 'map' },
{ id: 2, field: 'dog' },
{ id: 3, field: 'blubb' }
];
var filtered = _.filter(
data,
function(i) { return this.values.indexOf(i.field) > -1; },
{ "values": ["map", "dog"] } /* "context" with values to look for */
);
console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>