0

I am trying to filter an array of objects with Ramda and it is working almost as I planned but I have one small issue. My result is array with one filtered object which is great but I need only object itself not array around it.

My example data set:

const principlesArray = [
  {
    id: 1,
    harvesterId: "1",
    title: "Principle1"
  },
  {
    id: 2,
    harvesterId: "2",
    title: "Principle2"
  },
]

And that is my Ramda query:

R.filter(R.propEq('harvesterId', '1'))(principlesArray)

As a result I get array with one filtered element but I need object itself:

[{"id":1,"harvesterId":"1","title":"Principle1"}]

Any help will be appreciated

1 Answer 1

3

You can use R.find instead of R.filter, to get the first object found:

const principlesArray = [{"id":1,"harvesterId":"1","title":"Principle1"},{"id":2,"harvesterId":"2","title":"Principle2"}]

const result = R.find(R.propEq('harvesterId', '1'))(principlesArray)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

A more generic approach would be to create a function that takes a predicate used by R.where, pass the partially applied R.where to R.find, and then get the results by applying the function to the array:

const { pipe, where, find, equals } = R

const fn = pipe(where, find)

const principlesArray = [{"id":1,"harvesterId":"1","title":"Principle1"},{"id":2,"harvesterId":"2","title":"Principle2"}]

const result = fn({ harvesterId: equals('1') })(principlesArray)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

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

1 Comment

Using find instead filter was so obvious... In my case it should be enough. Thank you :)

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.