在数组Ramda中按ID查找对象

时间:2019-11-03 19:15:02

标签: javascript functional-programming ramda.js

例如,我有类似的东西:


FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build-env
...
RUN dotnet restore
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://privaterepo.somedomain.com/FindPackagesById()?id='somepackagename'&semVerLevel=2.0.0'.
  Connection refused

我需要找到ID为11的对象。我如何做:

COPY packages /root/.nuget/packages

但是由于地图,它返回const stuff = { "31": [ { "id": "11", "title": "ramda heeeelp" }, { "id": "12", "title": "ramda 123" } ], "33": [ { "id": "3", "title": "..." } ], "4321": [ { "id": "1", "title": "hello world" } ] } 。好的,我们可以检查对象是否未定义,但是不清楚。

1 个答案:

答案 0 :(得分:4)

获取对象的值,展平数组数组,并使用find和propEq获取对象:

const { pipe, values, flatten, find, propEq } = R

const findById = id => pipe(
  values,
  flatten,
  find(propEq({ id }))
)

const data = {"31":[{"id":"11","title":"ramda heeeelp"},{"id":"12","title":"ramda 123"}],"33":[{"id":"3","title":"..."}],"4321":[{"id":"1","title":"hello world"}]}

const result = findById('11')(data)

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