Javascript:按字符串数组过滤对象数组 [英] Javascript: filter array of objects by array of strings

查看:32
本文介绍了Javascript:按字符串数组过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更优雅的方法来做到这一点.假设我有一个像这样的对象数组:

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
  }
]

现在我想过滤 id 属性,以返回在另一个数组中匹配的所有对象

Now i want to filter on the id property, to return all objects with a match in another array

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]);
    }
 }
}

来自R,这看起来有点复杂,有没有办法用filter原型来做到这一点?像这样,但要比较的字符串数组而不是单个字符串:

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:

 var b = a.filter( function(item){return (item.id == "kpi03");} );

非常感谢!

推荐答案

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

You can use indexOf in filter, like this

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

示例

这篇关于Javascript:按字符串数组过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆