过滤对象数组基于另一种 - Ramda功能样式

时间:2018-02-27 20:49:06

标签: typescript ramda.js

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

let selected = [{id: 100}];

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

2 个答案:

答案 0 :(得分:2)

Ramda有一个内置函数,直接处理查找单个值。如果要查找列表中的所有内容,则需要稍微扩展一下。但是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中。

答案 1 :(得分:1)

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

// 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’)返回一个需要两个参数的函数。用于测试id属性的值,以及具有id属性

的对象

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

head返回索引0处的项目

您可以通过多种方式分解这些功能。无论你发现什么是最易读/可重用的

Have a play with the above code here

相关问题