3

I have an array of objects. I want to filter it to get objects, which any property contains the mathing string.

If my array is

 var data = [
 {"name: "John",
 "surname": "Smith"},
 {"name": "Peter",
 "surname: "Smithie"}]

I and filter with the string "Smi", it should return both items. If string is "John", only the first one.

This is my code:

var filtered = R.filter(R.where({ x: R.contains("Smi")}))(data);

I get error though:

Cannot read property 'indexOf' of undefined

Could someone help me out with my Ramda function? Must the something small I'm missing, I guess. Thanks in advance

1
  • The problem with this approach is that in where({x: contains('Smi')}), the x has no meaning. Ramda does not include a notion of "for any key" like this. Commented Sep 27, 2016 at 12:29

2 Answers 2

2

You could do something like this:

R.filter(R.pipe(R.values, R.any(R.contains('Smi'))))(data)

This is taking advantage of an undocumented feature of contains, though, which is meant to work on lists, not strings. But it does work.

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

Comments

1

I can not answer in Ramda but if you would like to implement the same functionality in JS you might easily do as follows;

var   data = [{"name": "John", "surname": "Smith"}, {"name": "Peter", "surname": "Smirnof"}],
getObjects = (d,f) => d.filter(o => Object.keys(o).some(k => o[k].includes(f)));
console.log(getObjects(data,"Smi"));
console.log(getObjects(data,"Jo"));

1 Comment

Like the Rambda-less solution, which is not significantly bigger.

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.