简体   繁体   中英

Filtering object array with ramda.js

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

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 .

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")); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM