Ramda - 从数组中提取对象

Ramda - extract object from array

我正在尝试使用 Ramda 过滤一组对象,它几乎按我的计划工作,但我有一个小问题。我的结果是包含一个过滤对象的数组,这很好,但我只需要对象本身而不是围绕它的数组。

我的示例数据集:

const principlesArray = [
  {
    id: 1,
    harvesterId: "1",
    title: "Principle1"
  },
  {
    id: 2,
    harvesterId: "2",
    title: "Principle2"
  },
]

这是我的 Ramda 查询:

R.filter(R.propEq('harvesterId', '1'))(principlesArray)

结果我得到了一个包含一个过滤元素的数组,但我需要对象本身:

[{"id":1,"harvesterId":"1","title":"Principle1"}]

任何帮助将不胜感激

您可以使用 R.find 而不是 R.filter,以获得找到的第一个对象:

const principlesArray = [{"id":1,"harvesterId":"1","title":"Principle1"},{"id":2,"harvesterId":"2","title":"Principle2"}]

const result = R.find(R.propEq('harvesterId', '1'))(principlesArray)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

一种更通用的方法是创建一个函数,该函数采用 R.where 使用的谓词,将部分应用的 R.where 传递给 R.find,然后通过应用获得结果数组的函数:

const { pipe, where, find, equals } = R

const fn = pipe(where, find)

const principlesArray = [{"id":1,"harvesterId":"1","title":"Principle1"},{"id":2,"harvesterId":"2","title":"Principle2"}]

const result = fn({ harvesterId: equals('1') })(principlesArray)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>