【问题标题】:lodash deep nested array filterlodash 深度嵌套数组过滤器
【发布时间】:2018-03-21 09:10:07
【问题描述】:

我有一个复杂的嵌套对象数组,我必须为此返回一个基于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},
                     {....} ,{...}
                    ]
              },
            ,{...}
         ]}
      ]

任何帮助表示赞赏!

【问题讨论】:

  • 你必须更清楚。你究竟会过滤什么?您能否发布一个示例,说明您在过滤此示例后会得到什么?
  • @OscarPaz 。抱歉现在更新了问题

标签: javascript arrays underscore.js lodash


【解决方案1】:

现在试试这个,

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

【讨论】:

  • 在应用过滤器后我需要数组的所有内容,但这会砍掉父对象并只返回子对象
  • 是的。父母反对。所以我们不能在过滤器中对对象进行切片。它仅适用于数组
  • 意味着这只返回子数组!不是嵌套
  • 根据您的结构,它将返回唯一的孩子
【解决方案2】:

如果我明白你在问什么,我认为这个函数应该可以解决问题:

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

这不是一个非常优雅的解决方案,但我最终得到的答案与您在原始帖子中所希望的相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2017-06-15
    • 2019-04-14
    • 2017-09-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多