简体   繁体   English

Ramda.js通过对象值创建过滤器函数

[英]Ramda.js create a filter function by object value

I'm learning FP and trying to figure this out: 我正在学习FP,并试图找出答案:

I have a list of users and need to create a function to filter them by name. 我有一个用户列表,需要创建一个函数来按名称过滤他们。 That's what I tried: 那就是我尝试过的:

let users = [{name: "rod"}]

let nameEq = R.prop("name")

let filterByName = R.compose( 
  R.filter(R._, users),
  nameEq
);

filterByName("rod")

This doesn't work because filter returns an array. 这不起作用,因为filter返回一个数组。 I guess I need to curry filter some way, but can't figure it out. 我想我需要以某种方式来咖喱filter ,但无法弄清楚。

If you are looking for a point free sort of style, how about this approach: 如果您正在寻找一种没有point free的样式,该方法如何:

const R = require('ramda');

// sample data
const data = [{name: 'rod', age: 25}, {name: 'chuck', age: 30}, {name: 'rod', age: 50}];


// Alternative 1: bake in the name and vary the data

const filterByName = R.compose(R.filter, R.propEq('name'));

const filterByRod = filterByName('rod');

// now supply the data
filterByRod(data); // => [ { name: 'rod', age: 25 }, { name: 'rod', age: 50 } ]


// Alternative 2: bake in the data, and then vary the name

const filterDataByName = R.compose(R.partialRight(R.filter, [data]), R.propEq('name'));

// now supply the name
filterDataByName('rod'); // => [ { name: 'rod', age: 25 }, { name: 'rod', age: 50 } ]

Believe you were aiming to do Alternative 2 above in your question. 相信您打算在您的问题中做以上替代方案2。

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

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