gpt4 book ai didi

javascript - 在数组 Ramda 中通过 id 查找对象

转载 作者:行者123 更新时间:2023-11-30 09:11:22 24 4
gpt4 key购买 nike

例如我有这样的东西:

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

我需要找到 ID 为 11 的对象。我是怎么做到的:

map(key => find(propEq('id', 11))(stuff[key]), keys(stuff)) 

但是由于映射,它返回 [{..object with id 11..}, undefined, undefined]。好的,我们可以检查对象是否未定义,但它并不像我想要的那样清晰。

最佳答案

获取对象的值,展开数组的数组,使用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>

关于javascript - 在数组 Ramda 中通过 id 查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com