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

JavaScript嵌套数组插入不存在元素时原有数据丢失问题求解

问题原因

你写的代码只保留了过滤出来的新增数据,没有合并原post中已有的likes、comments条目,才会导致原有数据丢失。

正确实现代码

const newPosts = posts.map(post => {
  // 先把已有id存为Set,大幅提升查找效率
  const existedLikeIds = new Set(post.likes.map(item => item.id))
  const existedCommentIds = new Set(post.comments.map(item => item.id))
  // 过滤出原数组中不存在的新增项
  const addLikes = likes.filter(item => !existedLikeIds.has(item.id))
  const addComments = comments.filter(item => !existedCommentIds.has(item.id))
  return {
    ...post,
    // 合并新增项与原有项,顺序可按需调整
    likes: [...addLikes, ...post.likes],
    comments: [...addComments, ...post.comments]
  }
})

console.log(newPosts)

补充说明

  1. 数据顺序可自行调整:
    • 新增项放前面:[...addLikes, ...post.likes]
    • 新增项放后面:[...post.likes, ...addLikes]
  2. 如果需要按id排序,合并后可追加sort方法:
    likes: [...addLikes, ...post.likes].sort((a,b) => a.id - b.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 06:15:04