嵌套数组中的lodash find属性不起作用

时间:2017-07-16 22:30:51

标签: javascript lodash

我有一个像这样的数组

sections: [
     {
        editing: false,
        id: 1234,
        rows: [
            {
               editing: false,
               id: 3435, 
               columns: [
                   {
                       id: 1535, 
                       elements: [
                           {
                              editing: true,
                              id: 4849
                           }
                       ]
                   }
               ]
            }
        ]
     },
]

并且我试图找到具有属性编辑的任何对象是真的。

以下代码有效,但仅适用于部分和行,但由于某种原因,它没有在elements数组中找到该属性

这是js,使用lodash

return _(state.sections)
      .thru(function(coll) {
          return _.union(coll, _.map(coll, 'rows'));
      })
      .thru(function(coll2) {
          return _.union(coll2, _.map(coll2, 'columns'));
      })
      .thru(function(coll3) {
          return _.union(coll3, _.map(coll3, 'elements'));
      })
      .flatten()
      .find({ editing: true });

1 个答案:

答案 0 :(得分:0)

在第一个thru之后,链的中间结果是一个由对象和数组组成的数组:

[
    { id: 1234, .... },
    [ { id: 3435, ... } ]
]

要获得您想要的内容,请将map来电替换为flatMap,然后在第一个thru之后将其返回:

[
    { id: 1234, .... },
    { id: 3435, ... }
]

如果对象没有undefinedcolumns,中间结果中会返回elements,您需要先使用compact删除这些内容执行查找:

return _(state.sections)
    .thru(function(coll) {
        return _.union(coll, _.flatMap(coll, 'rows'));
    })
    .thru(function(coll2) {
        return _.union(coll2, _.flatMap(coll2, 'columns'));
    })
    .thru(function(coll3) {
        return _.union(coll3, _.flatMap(coll3, 'elements'));
    })
    .compact()
    .find({ editing: true });