Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ramda – how to get nested array values

I am trying to get values from nested arrays using Ramda. 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.

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading