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

标签 javascript ramda.js

如何映射 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))

必须有一种方法可以结合使用mapfilterproppropEq来做到这一点、isNilreject 等。我似乎无法弄清楚。

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

我知道下面的代码不起作用,但这就是我所取得的进展:

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/

相关文章:

javascript 正则表达式,无组匹配或正向后查找

javascript - 使用Ramda(或其他功能库)使用indexOf过滤大数组对象?

javascript - HTML/JavaScript - 输入值不更新(Element.value = Null)

javascript - 如何从 JS 文件中的 WP-Config.php 读取全局变量

javascript - 使用 Ramda 根据条件更新嵌套值

JavaScript 数组对象排序未按预期工作

javascript - 在 Ramda 管道中使用 Promise.all

javascript - 展平数组,但使用子数组作为基础

javascript - SVG + CSS - 如何包含在 HTML 中以及缩放和颜色?

javascript - 暂停事件监听器