You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ID匹配合并posts、comments、likes三个JavaScript数组

三数组按ID合并实现方案

核心思路和你之前实现的两数组合并逻辑一致,只需要分别对posts条目下的likes、comments两个子数组做ID匹配合并即可。

基础实现(对齐原有参考逻辑)

直接沿用你原有find匹配的写法,逻辑简单直观,适合小数据量场景:

// 合并函数
const mergePostsData = (posts, likes, comments) => {
  return posts.map(({ likes: postLikes, comments: postComments, ...restPost }) => ({
    ...restPost,
    // 合并likes数组
    likes: postLikes.map(likeItem => ({
      ...likeItem,
      ...likes.find(like => like.id === likeItem.id)
    })),
    // 合并comments数组
    comments: postComments.map(commentItem => ({
      ...commentItem,
      ...comments.find(comment => comment.id === commentItem.id)
    }))
  }))
}

// 测试调用
const posts = [
  { 
    _id: 1,
    message: 'this is post one',
    likes: [ { id: 1111 }, { id: 2222 } ],
    comments: [ { id: 3333 }, { id: 4444 } ]
  }
]
const comments = [
  { id: 3333, message: 'this is comment 1' },
  { id: 4444, message: 'this is comment 2' }
]
const likes = [
  { id: 1111, user: 'Peter' },
  { id: 2222, user: 'John'  }
]

const newArray = mergePostsData(posts, likes, comments)
console.log(JSON.stringify(newArray, null, 2))

运行后输出结果和你要求的预期完全一致。

性能优化实现(适合大数据量场景)

如果likes、comments数组数据量较大,每次find都会遍历整个数组,效率较低,可以提前把两个数组转成ID为键的Map索引,查找时间复杂度降到O(1):

const mergePostsData = (posts, likes, comments) => {
  // 预构建索引Map
  const likesMap = new Map(likes.map(item => [item.id, item]))
  const commentsMap = new Map(comments.map(item => [item.id, item]))

  return posts.map(({ likes: postLikes, comments: postComments, ...restPost }) => ({
    ...restPost,
    likes: postLikes.map(likeItem => ({
      ...likeItem,
      ...likesMap.get(likeItem.id)
    })),
    comments: postComments.map(commentItem => ({
      ...commentItem,
      ...commentsMap.get(commentItem.id)
    }))
  }))
}

内容的提问来源于stack exchange,提问作者james williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:45:08