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

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

问题描述

我不知道是否有一个更优雅的方式来做到这一点。假设我有一个这样的对象数组:

  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


$ / code $ / pre
$ b $现在我想过滤 id 属性返回所有在另一个数组中有匹配的对象

  var kpis = [kpi03,kpi02]; 

我想出了这个解决方案:

  var b = []; 
for(j in kpis){
for(i in a){
if(a [i] .id == kpis [j]){
b.push( A [1]);


$ b $ / code $ / pre

来自R,有点复杂,有没有办法做到这一点与过滤器原型?像这样,但有一个字符串数组来比较,而不是一个单一的字符串:

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

非常感谢!

解决方案

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

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

示例


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

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:

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

Thanks a lot!

解决方案

You can use indexOf in filter, like this

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

Example

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

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