1

I am trying to get values from a nested object using Ramda but I just started to use it. To get the testArray I used:

R.find(R.propEq('type', 'checklist'))((data))

Data is another array with different types but I need to focus only on 'checklist' type. I would like to get only items which have property "checked": true.

This is my array which I am trying to transform.

const testArray = [{
  "type": "checklist",
  "data": {
    "items": [
      { "id": "r-1", "checked": true },
      { "id": "r-2", "checked": false }
    ]
  }
}]

Edit: I made another step using:

R.path(['data', 'items'])

I got only items that I can simply filter. But I am not sure if it is the correct way to do that.

Any help will be appreciated.

1 Answer 1

3

Here's one approach:

const checkedItems = pipe (
  find (propEq('type', 'checklist')),
  defaultTo ({data: {items: []}}),
  path (['data', 'items']),
  filter (prop ('checked'))
)

const testArray = [{type: "checklist", data: {items: [{id: "r-1", checked: true }, {id: "r-2", checked: false}]}}]

console .log (
  checkedItems (testArray)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script>const {pipe, find, propEq, defaultTo, path, filter, prop} = R</script>

Ramda (disclaimer: I'm one of its authors) is designed around this idea of a functional pipeline, where the result of one call is piped into the next. Here we use the propEq you started with, pipe it to a defaultTo call, which gives a sensible default if the previous step finds nothing, then to the path statement you used, and then finally to a filter call, which keeps only those where the checked property is true.

If you're absolutely certain about your data, you can skip the defaultTo step.

The filter call could also be filter (propEq ('checked', true)), but since prop ('checked') whould be returning a boolean, I went with the simpler version.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. So I was close... :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.