[英]lodash deep nested array filter
我有一个像这样复杂的嵌套对象数组,为此我必须基于attributeScore > 90
返回一个新的Array(filter)。 如何使用javascript .filter或lodash _.find()或_.some函数完成此操作?
trucks:[
{wheels:[
{name:"xyz",
mechanics: [
{engine:'50cc',
attributeScore:100},
{....} ,{...}
]
},
{name:"gcd",
mechanics: [
{engine:'80cc',
attributeScore:90},
{....} ,{...}
]
},
,{...}
]}
,{...}
]
我尝试过这样的过滤器
const fil = trucks.filter(function(item) {
return item.wheels.some(function(tag) {
return tag.mechanics.some(function(ques){
return ques.attributeScore <= 25;
});
});
});
但它返回一个空数组。 我期望的返回数组类型应该是
trucks:[
{wheels:[
{name:"xyz",
mechanics: [
{engine:'50cc',
attributeScore:100},
{....} ,{...}
]
},
,{...}
]}
]
任何帮助表示赞赏!
现在试试
var fill = trucks.map(function(item) {
return item.wheels.map(function(tag) {
return tag.mechanics.filter(function(ques){
return ques.attributeScore == 100;
});
});
});
如果我了解您的要求,我认为此功能应该可以解决问题:
_.map(trucks, truck => ({
...truck,
wheels: _.filter(_.map(truck.wheels, wheel => ({
...wheel,
mechanics: _.filter(wheel.mechanics, m => m.attributeScore > 90)
})), wheel => wheel.mechanics.length),
}));
这不是一个非常优雅的解决方案,但是我得到的答案与您在原始帖子中希望的相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.