簡體   English   中英

Ramda - 如何獲取嵌套數組值

[英]Ramda - how to get nested array values

我正在嘗試使用 Ramda 從嵌套的 arrays 獲取值。 我有多個組,如下例所示。 我需要在一個字符串數組中獲取所有sections的所有子項和所有childrenWithoutSections

const groups = [
   {
      "id":"10",
      "sections":[
         {
            "id":"1",
            "children":["10", "11"]
         },
         {
            "id":"2",
            "children":["12"]
         }
      ],
      "childrenWithoutSections":["1", "2"]
   },
   {
      "id":"11",
      "sections":[
         {
            "id":"3",
            "children":["13", "14"]
         },
         {
            "id":"4",
            "children":["15"]
         }
      ],
      "childrenWithoutSections":["3", "4"]
   }
]

我從這樣的事情開始:

R.pipe(
  R.pluck(['childrenWithoutSections']),
  R.flatten
)(groups)

結果,我從一個必需的鍵中獲取了所有子項,但我不知道如何從sections/children項中獲取嵌套值?

除了評論中的建議,我們還可以寫一個這樣的免點版本:

 const extract = chain ( lift (concat) ( pipe (prop ('sections'), pluck('children'), flatten), prop ('childrenWithoutSections') ) ) const groups = [{id: "10", sections: [{id: "1", children: ["10", "11"]}, {id: "2", children: ["12"]}], childrenWithoutSections: ["1", "2"]}, {id: "11", sections: [{id: "3", children: ["13", "14"]}, {id: "4", children: ["15"]}], childrenWithoutSections: ["3", "4"]}] console.log (extract (groups))
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.min.js"></script> <script> const {chain, lift, concat, pipe, prop, pluck, flatten} = R </script>

另一種選擇是使用R.juxtsectionschildrenWithoutSections中獲取children ,然后將結果展平。 通過鏈接結果,我們得到了值數組。

 const {chain, pipe, juxt, prop, pluck, flatten } = R const fn = chain(pipe( juxt([ pipe(prop('sections'), pluck('children')), prop('childrenWithoutSections') ]), flatten, )) const groups = [{id: "10", sections: [{id: "1", children: ["10", "11"]}, {id: "2", children: ["12"]}], childrenWithoutSections: ["1", "2"]}, {id: "11", sections: [{id: "3", children: ["13", "14"]}, {id: "4", children: ["15"]}], childrenWithoutSections: ["3", "4"]}] const result = fn(groups) console.log(result)
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.2/ramda.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM