[英]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.juxt
从sections
和childrenWithoutSections
中获取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.