2017-07-16 56 views
1

我有像這樣lodash找到嵌套數組屬性不工作

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

和IM試圖找到一個屬性編輯任何對象是真正的數組。

下面的代碼工作,但僅用於部分和行,但由於某些原因它不是找到元件陣列

這是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 }); 

回答

0

第一後thru鏈的中間結果是由對象和數組的數組:

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

爲了得到你想要的東西,更換map個電話與flatMap,然後這些第一thru後返回此:

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

一樣會有undefined在中間結果返回如果對象沒有columnselements,您將需要使用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 }); 
+0

完美,非常感謝,我完全忘記了地圖返回一個數組 – Dan