Ramda - 从数组中提取对象

问题描述 投票:0回答:1

我正在尝试用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"}]

任何帮助将被感激

ramda.js
1个回答
3
投票

你可以用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>
© www.soinside.com 2019 - 2024. All rights reserved.