[英]Ramda - how to get nested array values
I am trying to get values from nested arrays using Ramda.我正在尝试使用 Ramda 从嵌套的 arrays 获取值。 I have multiple groups like in the example below.
我有多个组,如下例所示。 I need to get all children from all
sections
and all childrenWithoutSections
in one array of strings.我需要在一个字符串数组中获取所有
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"]
}
]
I started with something like this:我从这样的事情开始:
R.pipe(
R.pluck(['childrenWithoutSections']),
R.flatten
)(groups)
And as a result, I got all the children from one required key but I have no idea how to get nested values from sections/children
?结果,我从一个必需的键中获取了所有子项,但我不知道如何从
sections/children
项中获取嵌套值?
As well as the suggestions in the comments, we can also write a point-free version of this:除了评论中的建议,我们还可以写一个这样的免点版本:
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>
Another option is to use R.juxt
to get children
from the sections
, and the childrenWithoutSections
and then flattening the results.另一种选择是使用
R.juxt
从sections
和childrenWithoutSections
中获取children
,然后将结果展平。 By chaining the results we get the array of values.通过链接结果,我们得到了值数组。
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.