基于另一个过滤对象数组 - Ramda 函数式风格

Filter object array based on another - Ramda functional style

let arr = [
{
 id: 100,
 name: 'bmw'
},
{
 id: 101,
 name" 'porsche'
}
];

let selected = [{id: 100}];

华美达根据输入(列表,已选择)获取过滤列表的方法是什么?

我的做法是将其分解为几个部分。

// a function to grab the the id out of selected (index of 0, key of 'id')
const selectedId = path([0, 'id'])

const selectedValue = (selected, options) =>
  filter(propEq('id', selectedId(selected)), options)

selectedValue(selected, arr) // [{"id": 100, "name": "bmw"}]

根据我的喜好,这有点难读,所以我会重新组合一些函数,并使用 head 从数组中获取结果

const hasIdOf = pipe(selectedId, propEq('id'))

const selectedValueB = (selected, options) => pipe(
  filter(hasIdOf(selected))),
  head
)(options)

selectedValueB(selected, arr) // {"id": 100, "name": "bmw"}

propEq(‘id’) returns 一个多了两个参数的函数。用于测试 id 属性 的值,以及具有 id 属性

的对象

pipe 将许多函数组合在一起,在这种情况下,它将 options 传递给 filter(...),并将结果传递给 head

head returns 索引 0 处的项目

您可以通过多种方式分解函数。无论您找到什么最多 readable/reusable

Have a play with the above code here

Ramda 有一个函数 built-in 直接处理查找单个值。如果您想找到列表中的所有内容,则需要稍微扩展一下。但是 whereEq 测试对象以查看所有属性是否与示例对象中的属性匹配。所以你可以这样做:

const {find, whereEq, map} = R;

const arr = [
  {id: 100, name: 'bmw'},
  {id: 101, name: 'porsche'},
  {id: 102, name: 'ferrari'},
  {id: 103, name: 'clunker'}
]

console.log(find(whereEq({id: 101}), arr))

const choose = (all, selected) => map(sel => find(whereEq(sel), all), selected)

console.log(choose(arr, [{id: 101}, {id: 103}]))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

根据您打算如何使用它,您可能希望将 choose 包装在 curry 中。