请问js这样的数组如何合并

{
   con:[
      {content:"dsa",evaId:29,id:38,types:1},
      {content:"dfsd",evaId:30,id:39,types:1},
      {content:"dsf",evaId:33,id:42,types:1},
      {content:"sd213",evaId:37,id:47,types:1}
   ],
   body:[
      {content:"dsa",id:30,types:1},
      {content:"dfsd",id:39,types:1},
      {content:"dsf",id:33,types:1},
      {content:"sd213",id:37,types:1},
      {content:"sd213",id:29,types:1}
   ],
   img:[
      {content:"dsa",evaId:30,id:21,types:1},
      {content:"dfsd",evaId:29,id:15,types:1},
      {content:"dsf",evaId:33,id:12,types:1},
   ]

}

 请问怎么通过body的id合并其他两个数组的evaId来合并成一个数组?
阅读 2.4k
2 个回答
var id;//目标id
let arr1=body.filter(item=>item.id==id);
let arr2=con.filter(item=>item.id==id);
let arr3=img.filter(item=>item.id==id);
var arr=arr1.concat(arr2,arr3); //合并后的数组

上述代码可用函数简单封装一下。

思路供参考

var map = body.reduce((m, {id}) => m.set(id, []), new Map())
con.concat(img).reduce((m, x) => {
  let list = m.get(x.evaId)
  if (list) { list.push(x) }
  return m
}, map)

console.log(Array.from(map.values()).filter(x => x.length > 0))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题