简体   繁体   English

Lodash深层嵌套数组过滤器

[英]lodash deep nested array filter

I have a complex nested array of objects like this for which I have to return a new Array(filter) based on attributeScore > 90 . 我有一个像这样复杂的嵌套对象数组,为此我必须基于attributeScore > 90返回一个新的Array(filter)。 How will I accomplish this using the javascript .filter or the lodash _.find() or _.some function ? 如何使用javascript .filter或lodash _.find()或_.some函数完成此操作?

trucks:[
     {wheels:[
             {name:"xyz",
              mechanics: [
                     {engine:'50cc',
                     attributeScore:100},
                     {....} ,{...}
                    ]
              },
              {name:"gcd",
              mechanics: [
                     {engine:'80cc',
                     attributeScore:90},
                     {....} ,{...}
                    ]
              }, 
            ,{...}
         ]}
         ,{...}
      ]

I tried a filter like this 我尝试过这样的过滤器

const fil = trucks.filter(function(item) {
    return item.wheels.some(function(tag) {
      return tag.mechanics.some(function(ques){
        return ques.attributeScore <= 25;
      });
    });
  });

but it returns an empty array . 但它返回一个空数组。 My expected return array type should be 我期望的返回数组类型应该是

trucks:[
     {wheels:[
             {name:"xyz",
              mechanics: [
                     {engine:'50cc',
                     attributeScore:100},
                     {....} ,{...}
                    ]
              },
            ,{...}
         ]}
      ]

Any help appreciated!! 任何帮助表示赞赏!

Try this now, 现在试试

var fill = trucks.map(function(item) {
    return item.wheels.map(function(tag) {
      return tag.mechanics.filter(function(ques){
        return ques.attributeScore == 100;
      });
    });
  });

If I understand what you are asking, I think this function should do the trick: 如果我了解您的要求,我认为此功能应该可以解决问题:

_.map(trucks, truck => ({ 
  ...truck,
  wheels: _.filter(_.map(truck.wheels, wheel => ({
    ...wheel,
    mechanics: _.filter(wheel.mechanics, m => m.attributeScore > 90)
  })), wheel => wheel.mechanics.length),
}));

It's not a terribly elegant solution, but I wind up with the same answer as you were hoping for in your original post. 这不是一个非常优雅的解决方案,但是我得到的答案与您在原始帖子中希望的相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM