2016-03-10 68 views
0

使用lodash將數據(如下面的數據)映射到單個level2對象數組中的快速方式是什麼?使用lodash將數組中的數據映射到單個數組的好方法是什麼?

SomeObject = { 
    name: 'someObject', 
    level1: [ 
     { 
      id: '1', 
      level2: [ 
       { someValue: 'example1'}, 
       { someValue: 'example2'}, 
       { someValue: 'example3'}, 
       { someValue: 'example4'} 
      ] 
     }, 
     { 
      id: '2', 
      level2: [ 
       { someValue: 'example5' }, 
       { someValue: 'example6' }, 
       { someValue: 'example7' }, 
       { someValue: 'example8' } 
      ] 
     }, 
     { 
      id: 'n', 
      level2: [ 
       { someValue: 'examplen' }, 
      ] 
     } 
    ] 
} 

輸出:

[ 
'example1', 
'example2', 
'example3', 
'example4', 
'example5', 
'example6', 
'example7', 
'example8', 
'examplen', 
] 

忽略: Stackflow是比我聰明,所以我必須輸入更多的非編碼的東西它停止抱怨。所以我會輸入更多,以便我可以發佈。

回答

3

您可以使用flatMap()收集所有的「級別2」數組到一個單一的陣列,然後用一個簡單的map()

_.map(_.flatMap(SomeObject.level1, "level2"),"someValue") 
+0

我的輸出提取「someValue中」性質是錯誤的,並對其進行了編輯,以正確的輸出。對困惑感到抱歉!呃它應該是一串字符串。 – Calvin

+0

然後只需添加另一個地圖()來提取someValue屬性。 – MrFlick

+0

這將創建一個數組的數組,然後扁平化處理它。天才。謝謝 – Calvin

相關問題