lodash深嵌套数组过滤器

时间:2018-03-21 09:10:08

标签: javascript arrays underscore.js lodash

我有一个复杂的嵌套对象数组,我必须根据attributeScore > 90返回一个新的数组(过滤器)。我将如何使用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},
                     {....} ,{...}
                    ]
              },
            ,{...}
         ]}
      ]

任何帮助表示赞赏!!

2 个答案:

答案 0 :(得分:1)

立即试试,

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

答案 1 :(得分:0)

如果我理解你的要求,我认为这个功能可以解决问题:

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

这不是一个非常优雅的解决方案,但我最终得到了你原来的帖子所希望的答案。