Ramda - 使用来自其他数组的 ID 获取对象数组

Ramda - get array of objects using ids from other array

我有两组数据,我想使用第一组从第二组获取对象数组。我试图自己处理它,但我错过了几个步骤。

这是要使用的一组 ID:

const idSet = {
  "41": {
    "id": "41"
  },
  "42": {
    "id": "42"
  },
  "43": {
    "id": "43"
  }
}

这是第二组:

const nodes = {
  "3": {
    "nodeCommentId": 3,
    "nodeId": 43,
  },
  "4": {
    "nodeCommentId": 4,
    "nodeId": 41
  },
  "6": {
    "nodeCommentId": 6,
    "nodeId": 42
  },
  "7": {
    "nodeCommentId": 7,
    "nodeId": 44
  },
}

我需要按 idnodeId 进行搜索,所以我尝试使用类似这样的方法来仅从第一组中获取 ID:

const ids = R.compose(
  R.values(),
  R.pluck('id')
)(idSet)

我还想到了类似的东西:R.filter(R.compose(R.flip(R.contains)(ids), R.prop('nodeId')), nodes);

但是我有 nodeId,它是一个数字而不是一个字符串,而且我需要一个没有键的对象数组。

期望的输出:

[
  {
    nodeCommentId: 3,
    nodeId: 43
  },
  {
    nodeCommentId: 4,
    nodeId: 41
  },
  {
    nodeCommentId: 6,
    nodeId: 42
  }
]

任何帮助将不胜感激。

这可能太难用了,但它可能是一个不错的解决方案的开始:

const nodesById = (idSet) => {
  const ids = map (Number, pluck ('id') (values (idSet)))
  return pipe (values, filter (pipe (prop('nodeId'), contains(__, ids))))
}

const idSet = {41: {id: "41"}, 42: {id: "42"}, 43: {id: "43"}}
const nodes = {3: {nodeCommentId: 3, nodeId: 43, }, 4: {nodeCommentId: 4, nodeId: 41}, 6: {nodeCommentId: 6, nodeId: 42}, 7: {nodeCommentId: 7, nodeId: 44}}

console .log (
  nodesById (idSet) (nodes)
)
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script>const {map, pluck, values, pipe, filter, prop, contains, __} = R </script>

我敢肯定,只要稍加努力,我们就可以做到这一点,但我怀疑这是否有助于提高可读性。

idSet转换为数字数组,然后用户R.innerJoin得到匹配nodeId:

的项目

const { pipe, values, pluck, map, innerJoin, __, curry } = R

const getIds = pipe(values, pluck('id'), map(Number))

const getNodesById = curry((idSet, nodes) => 
  pipe(
    values, 
    innerJoin(
      ({ nodeId }, id) => nodeId === id, 
      __,
      getIds(idSet)
    )
  )(nodes)
)

const idSet = {41: {id: "41"}, 42: {id: "42"}, 43: {id: "43"}}
const nodes = {3: {nodeCommentId: 3, nodeId: 43, }, 4: {nodeCommentId: 4, nodeId: 41}, 6: {nodeCommentId: 6, nodeId: 42}, 7: {nodeCommentId: 7, nodeId: 44}}

const result = getNodesById(idSet)(nodes)

console.log(result)
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>