如何解决根据javascript中的对象过滤对象数组
我想知道如何在javascript中过滤对象数组。
如何根据条件进行过滤-
对于count
和w1
对象, 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));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。