使用 Ramda 在 js 中对 JSON 个对象进行通用过滤

generic filtering of JSON objects in js using Ramda

我希望实现尽可能具有通用性和功能性(就像在函数式编程中一样),但一般来说,我希望 json 反对具有以下结构:

[
 {
   id: number,
   prop1: string,
   prop2: number,
   prop3: string,
   ...,
   propN: string
 },
 ...
]

(基本上,包含 N 个属性的对象数组,一些映射到字符串,另一些映射到数字)

我正在尝试实现一组通用函数,以便能够为此实现一些目标:

var filteredResult = filter(by(property, value, lt\gt\eq\contains), collection);

基本上,我想 return 一个具有相同对象结构的数组,由我传递给 by() 的 属性 字符串以及值(要么是一个字符串或数字)以及我想要执行的比较类型。

一般来说,对于数字,我希望能够过滤结果,其中 属性 值是我传递的值的 greater/lessthan/in 范围,带有字符串或字符串数​​组,我我想知道 属性 值是否包含我传递给 by() 的值。

由于我是 FP 的新手,我正在努力格式化我的代码以利用 Ramda 提供的自动柯里化功能,并且在传递我想要的参数时我无法组合不同的函数。

例如,我写了这个函数:

var byProperty = function(p) {return R.useWith(R.filter, R.propEq(p), R.identity)};

但是当我尝试这样使用它时:

var property = 'prop1', value = 15;
console.log( byProperty( property, value, collection ) );

我得到一个函数而不是过滤后的数组。

我知道我在这里遗漏了一些微不足道的东西,但我很难理解 Ramda 中传递值和函数的方式。

but when I try to use it like console.log( byProperty( property, value, collection ) ) I get a function instead of the filtered array.

是的,因为您的函数只接受一个参数,returns 一个函数。您可以这样调用它:

console.log( byProperty(property)(value, collection) );

但这可能不是您想要的。另外,我认为 useWith 在这里是错误的工具,您只需要一个 compose:

var byProperty = R.compose(R.filter, R.propEq);

虽然仍然需要这样称呼

console.log( byProperty(property, value)(collection) );

为此有 an open issue,但柯里化和组合可变参数函数并非易事。最好的可能是

var byProperty = R.curryN(3, function(p, v, c) { return R.filter(R.propEq(p, v), c); });