gpt4 book ai didi

javascript - 使用 Ramda 将 id 数组映射到具有这些 id 的对象

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

如何映射一个 id 数组:

['a', 'b', 'c']

到另一个数组中的相应对象:

[
{
id: 'a',
label: 'Letter A'
},
{
id: 'b',
label: 'Letter B'
},
...
...
]

另一个数组可能比第一个数组有更多的对象。

具有挑战性的部分是我想以“Ramda 方式”来做到这一点。

如果我不使用 RamdaJS,它会是这样的:

const ids = ['a', 'b']
const objects = [{ id: 'a', label: 'Letter A' }, { id: 'b', label: 'Letter B' }, { id: 'c', label: 'Letter C' }]
const whatIWant = objects.filter(obj => ids.includes(obj.id))

必须有办法结合mapfilterproppropEqisNilreject 等。我就是想不通。

“保留/过滤ids数组中包含id的对象”

我知道下面的代码不起作用,但这就是我得到的程度:

const doFilter = (ids, objects) => (
map(
find(
// ??? Where the object.id is included in ids[]
)(objects)
)(ids)
)

谢谢

最佳答案

ref

const ids = ['a', 'b'];
const objects = [{ id: 'a', label: 'Letter A' }, { id: 'b', label: 'Letter B' }, { id: 'c', label: 'Letter C' }];
console.log(R.flip(R.contains)(ids)('a'));
console.log(R.flip(R.contains)(ids)('c'));
console.log(R.filter(R.compose(R.flip(R.contains)(ids), R.prop('id')), objects));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>


ref2

const ids = ['a', 'b'];
const objects = [{ id: 'a', label: 'Letter A' }, { id: 'b', label: 'Letter B' }, { id: 'c', label: 'Letter C' }];

const joinById = R.innerJoin(
(o, id) => o.id === id
);

const result = joinById(objects, ids);

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

关于javascript - 使用 Ramda 将 id 数组映射到具有这些 id 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899484/

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