如何根据条件获取对象数组

问题描述

如何基于javascript中的条件获取对象数组。

我有一个数组对象obj,其中每个对象w1,w2 ... wn的计数应大于2。

如何基于javascript中的对象键过滤数组对象。

function getobject (obj1){
  var result = obj1.filter(e=> e.w1.count > 2 && e.w2.count > 2);
  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": 1,"amount": 503.0},... wn
"totalcount": 5
},{
"memberid": "s3","w1":{"count": 3,"amount": 0.0},"w2":{"count": 3,"qty": 4,... wn
"totalcount": 6
}
]

预期输出

[
{
"memberid": "s3",... wn
"totalcount": 6
}
]

解决方法

您可以基于每个对象中的每个值过滤数组,这些值不是对象,或者如果对象是count大于2的对象:

const obj1 = [{
    "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": 1,"amount": 503.0
    },"totalcount": 5
  },{
    "memberid": "s3","w1": {
      "count": 3,"amount": 0.0
    },"w2": {
      "count": 3,"qty": 4,"totalcount": 6
  }
];

const out = obj1.filter(o => Object.values(o).every(v => typeof v != 'object' || v.count > 2));

console.log(out);

,

您需要遍历对象键,过滤掉无效的键

function getObject(obj1) {
  // filter
  return obj1.filter(e =>
    // based on the entries [key,value]
    Object.entries(e)
    // filter out entries where key is not a w followed by a number  
    .filter(val => val[0].match(/w\d+/))
    // if every selected entry as a count > 2
    .every(val => val[1].count > 2)
  );
}

const obj1=[{memberid:"s1",w1:{count:1,qty:1},w2:{count:0,qty:0},totalcount:1},{memberid:"s2",w1:{count:2,qty:2,amount:400},w2:{count:1,amount:503},totalcount:5},{memberid:"s3",w1:{count:3,amount:0},w2:{count:3,qty:4,totalcount:6}];

const output = this.getObject(obj1);
console.log(output)

有用的功能文档: Object.entriesArray.filterArray.every

,
function getObject (obj1) {
  var result = obj1.filter((e) => {
    var isValid = false;
    var i = 1;
    while (e['w' + i]) {
      if (e['w' + i].count > 2) {
        isValid = true;
      } else {
        isValid = false;
        break;
      }
      i++;
    }
    return isValid;
  });
  return result;
}