Javascript:按字符串数组过滤对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28138139/
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
Javascript: filter array of objects by array of strings
提问by Schw4rz
I wonder if there is a more elegant way of doing this. Suppose i have an array of objects like this:
我想知道是否有更优雅的方式来做到这一点。假设我有一个像这样的对象数组:
a = [
{
"id": "kpi02",
"value": 10
},
{
"id": "kpi02",
"value": 30
},
{
"id": "kpi02",
"value": 11
},
{
"id": "kpi02",
"value": 33
},
{
"id": "kpi03",
"value": 1
},
{
"id": "kpi03",
"value": 0.5
},
{
"id": "kpi04",
"value": 0.5
}
]
Now i want to filter on the id
property, to return all objects with a match in another array
现在我想过滤该id
属性,以返回在另一个数组中匹配的所有对象
var kpis = ["kpi03", "kpi02"];
I came up with this solution:
我想出了这个解决方案:
var b = [];
for (j in kpis) {
for (i in a) {
if (a[i].id == kpis[j]) {
b.push(a[i]);
}
}
}
Coming from R, this seems a bit complicated, is there any way to do that with the filter
prototype? Like this but with an array of strings to compare with instead of a single string:
来自R,这似乎有点复杂,有没有办法用filter
原型来做到这一点?像这样,但要与一个字符串数组而不是单个字符串进行比较:
var b = a.filter( function(item){return (item.id == "kpi03");} );
Thanks a lot!
非常感谢!
回答by Alexander T.
回答by itaydafna
回答by Amit Joki
Just make use of Array.indexOf
只要利用 Array.indexOf
var b = a.filter(function(item){return kpids.indexOf(item.id) > -1 });
Array.indexOf
returns the index of the argument passed in the array on which indexOf
is being called on. It returns -1
if there isn't the element which we are looking for.
Array.indexOf
返回在indexOf
被调用的数组中传递的参数的索引。-1
如果没有我们正在寻找的元素,它就会返回。
So, we make sure that it index is greater than -1
因此,我们确保它的索引大于 -1