根据javascript中的对象过滤对象数组

问题描述

我想知道如何在javascript中过滤对象数组。

如何根据条件进行过滤-

对于countw1对象,

w2应该都大于0

totalcount应该大于2。

但是除了指定w1或w2之外,还有其他方法可以执行此操作,因为将会有w1,w2,w3 ... wn次

function getobject (obj1){
  var result = obj1.filter(e=>e.totalcount > 2 && e.w1.count > 0 && e.w2.count > 0);
  return result;
}
var output = this.getobject(obj1);

var obj1=[
 {
"memberid": "s1","w1":{"count": 1,"qty": 1},"w2":{"count": 0,"qty": 0},... wn
"totalcount": 1
 },{
"memberid": "s2","w1":{"count": 2,"qty": 2,"amount": 400.0},"w2":{"count": 3,"amount": 503.0},... wn
"totalcount": 5
},{
"memberid": "s3","w1":{"count": 3,"amount": 0.0},"qty": 4,... wn
"totalcount": 6
}
]

预期产量

[
{
"memberid": "s2","totalcount": 5
},"totalcount": 6
}

]

解决方法

您可以使用filter(),然后使用spread operator获取所有的“ w”,并使用Object.values()获取其中的一个数组,并使用some()检查是否count等于0。 并检查totalcount属性的值

var arr = [
    {
  "memberid": "s1","w1":{"count": 1,"qty": 1},"w2":{"count": 0,"qty": 0},"totalcount": 1
    },{
  "memberid": "s2","w1":{"count": 2,"qty": 2,"amount": 400.0},"w2":{"count": 3,"amount": 503.0},"totalcount": 5
  },{
  "memberid": "s3","w1":{"count": 3,"amount": 0.0},"qty": 4,"totalcount": 6
  }
 ]

 const res = arr.filter(({ memberid,totalcount,...rest }) => {
    return !Object.values(rest).some(({ count }) => count === 0) && totalcount > 2;
 })

 console.log(res);

参考:

filter()
Object.values()
some()

,

您可以在数组上使用过滤器。对于检查计数,我使用Array#filter。因为我不知道存在哪些键,所以我使用了一个正则表达式,该正则表达式会打在所有“ w”和一个数字上。

function getObject (obj1){
  var result = obj1.filter(e=> {
      if (e.totalcount <= 2) 
          return false;
      return Object.keys(e).every(key => !key.match(/^w[0-9]+$/) || e[key].count>0);
  });
  return result;
}

var obj1=[
 {
"memberid": "s1","totalcount": 1
 },{
"memberid": "s2","totalcount": 5
},{
"memberid": "s3","totalcount": 6
},{
"memberid": "s4","w3":{"count": 2,"w4":{"count": -3,"totalcount": 6
}
];

console.log(getObject (obj1));