JS合并多个对象数组

  let arr1 = [
    {id: '1', test: '1'},
    {id: '2', test: '2'},
    {id: '3', test: '3'},
    {id: '4', test: '4'}
  ]
  let arr2 = [
    {id: '1', test2: '1'},
    {id: '2', test2: '2'},
    {id: '3', test2: '3'},
    {id: '5', test2: '5'}
  ]
  let arr3 = [
      {id: '1', test2: '1'},
      {id: '2', test2: '2'},
      {id: '3', test2: '3'},
      {id: '6', test2: '6'}
  ]
  let arr4 = [
      {id: '1', test2: '1'},
      {id: '2', test2: '2'},
      {id: '3', test2: '3'},
      {id: '7', test2: '7'}
  ]
  let arrList = [arr1,arr2,arr3,arr4]
  // 欲合并后得到如下数组:
  // [
  //     {id: '1', test: '1',test2: '1'},
  //     {id: '2', test: '2', test2: '2'},
  //     {id: '3', test: '3', test2: '3'},
  //     {id: '4', test: '4'},
  //     {id: '5', test2: '5'},
  //     {id: '6', test2: '6'},
  //     {id: '7', test2: '7'}
  // ]
	
	 function ArrayAssign(arg1,arg2,id){
	     let obj = new Object()
	     let arr_copy1 = []
	     let arr_copy2 = []
	     // 在下面的遍历中,若arg1为空数组,则不能合并。
	     // 故先判断,预防空数组出现,长度更长者在外层。
	     if(arg1.length >= arg2.length){ 
	         arr_copy1 = arg1
	         arr_copy2 = arg2
	     } else {
	         arr_copy1 = arg2
	         arr_copy2 = arg1
	     }
	     arr_copy1.forEach((item)=>{
	         obj[item[id]] = item
	         arr_copy2.forEach((item2)=>{
	             if(item2[id] == item[id]){
	                 obj[item[id]] = Object.assign(item,item2)
	             } else {
	                 if(!obj.hasOwnProperty(item2[id])){
	                     obj[item2[id]] = item2
	                 }
	             }
	         })
	     })
	     return Object.values(obj)
	 }
	 let all = arrList.reduce((prev,cur,index,arr3) => { //  前一项、当前项、下标、数组名
      return ArrayAssign(prev, cur,'id');// 传入要合并的数组,和两个数组元素中都唯一的键
  	})
  	console.log(all)	

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值