Ramda - 如何获取嵌套数组值

Ramda - how to get nested array values

我正在尝试使用 Ramda 从嵌套数组中获取值。我有多个组,如下例所示。我需要从一个字符串数组中获取所有 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>