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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:28:50  来源:igfitidea点击:

Javascript: filter array of objects by array of strings

javascriptarraysfilter

提问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 idproperty, 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 filterprototype? 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.

You can use indexOfin filter, like this

您可以在过滤器中使用indexOf,就像这样

var res = a.filter(function (el) {
  return kpis.indexOf(el.id) >= 0; 
});

Example

例子

回答by itaydafna

Another nice alternative is using .filterwith .includes:

另一个不错的选择是使用.filter.includes

var result = a.filter(item => kpis.includes(item.id))

回答by Amit Joki

Just make use of Array.indexOf

只要利用 Array.indexOf

var b = a.filter(function(item){return kpids.indexOf(item.id) > -1 });

Array.indexOfreturns the index of the argument passed in the array on which indexOfis being called on. It returns -1if 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