如何映射 ids 数组:
['a', 'b', 'c']
到另一个数组中对应的对象:
[
{
id: 'a',
label: 'Letter A'
},
{
id: 'b',
label: 'Letter B'
},
...
...
]
另一个数组的对象数量可能多于第一个数组的 id。
具有挑战性的部分是我想用“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))
必须有一种方法可以结合使用map
、filter
、prop
、propEq
来做到这一点、isNil
、reject
等。我似乎无法弄清楚。
“保留/过滤 ids 数组中包含 ids 的对象”
我知道下面的代码不起作用,但这就是我所取得的进展:
const doFilter = (ids, objects) => (
map(
find(
// ??? Where the object.id is included in ids[]
)(objects)
)(ids)
)
谢谢
最佳答案
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>
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/