以元素id为合并标准 合并两个数组

借助数组方法中的reduce方法,先看示例:

var arr1 = [{ id: 1, age: '11' },{ id: 2, age: '22' },{ id: 3, age: '33' }]
var arr2 = [{ id: 3, name: 'CC' },{ id: 1, name: 'AA' },{ id: 2, name: 'BB' }]
const mergedArray = arr2.reduce((merge, cur) => {
  const target = merge.find(e => e.id === cur.id);
  if (target) {
    Object.assign(target, cur);
  } else {
    merge.push(cur);
  }
  return merge;
}, arr1);
console.log(mergedArray)

以上代码块的结果为:

[
  { id: 1, age: '11', name: 'AA' },
  { id: 2, age: '22', name: 'BB' },
  { id: 3, age: '33', name: 'CC' }
]

解释:

  1. reduce()方法:
    reduce()方法是处理数组的方法,它接收一个函数和一个初始值,然后将数组中的每个元素和初始值当作参数传入这个函数中进行处理,最后返回和初始值相同类型的值。
    语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

  2. arr2.reduce(function(merge,cur),arr1)
    将arr1作为merge数组的初始值,依次将当前merge数组和当前元素curr传入function中进行处理。

  3. function中的操作
    const target = merge.find(e => e.id === cur.id);
    在merge中寻找与当前元素curr相同id的对象,如果有相同属性就assign,没有就push。

posted @ 2020-05-06 17:18  兔子大叔  阅读(616)  评论(0编辑  收藏  举报