简体   繁体   English

使用ramda.js过滤对象数组

[英]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. 我并使用字符串“ Smi”进行过滤,它应该返回两个项目。 If string is "John", only the first one. 如果字符串是“ John”,则仅第一个。

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? 有人可以帮我解决我的Ramda功能吗? 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. 但是,这利用了contains的未记录功能,该功能旨在在列表上工作,而不是在字符串上工作。 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; 我无法在Ramda中回答,但是如果您想在JS中实现相同的功能,则可以轻松地执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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