javascript - 如何根据条件获取对象数组
问题描述
如何根据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, "qty": 2, "amount": 503.0},
... wn
"totalcount": 5
},
{
"memberid": "s3",
"w1":{"count": 3, "qty": 2, "amount": 0.0},
"w2":{"count": 3, "qty": 4, "amount": 503.0},
... wn
"totalcount": 6
}
]
预期输出:
[
{
"memberid": "s3",
"w1":{"count": 3, "qty": 2, "amount": 0.0},
"w2":{"count": 3, "qty": 4, "amount": 503.0},
... 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,
"qty": 2,
"amount": 503.0
},
"totalcount": 5
},
{
"memberid": "s3",
"w1": {
"count": 3,
"qty": 2,
"amount": 0.0
},
"w2": {
"count": 3,
"qty": 4,
"amount": 503.0
},
"totalcount": 6
}
];
const out = obj1.filter(o => Object.values(o).every(v => typeof v != 'object' || v.count > 2));
console.log(out);
推荐阅读
- docker - 在 spark cassandra 中使用数据帧创建键空间时出错
- facebook-opengraph - Disqus 推荐中未更新 og:image 值的更改
- javascript - PHP 转到另一个页面并 getElementById
- python - 如何从 Qlistwidget 中选择项目,并更新 Pyqt5 中的文本框?
- c - 我一直在 Visual Studio 代码上收到此错误(WildcardPatternException)
- apache - .htaccess 重写隐藏参数并保持文件相同
- swift - 如何在 Swift 中处理解析 JSON 错误
- java - 无法从 WebView 下载 pdf 文件。始终下载 .bin 文件。我签入了具有 android 10 的一加手机
- firebase - 在 null 上调用了方法“[]”。接收方:空。尝试调用:[]("myuserId")
- javascript - 将不相交的数组合并为一个数组