7

need

There are two object arrays A and B. Now you need to merge the objects in the two arrays, replace if there is, add if not, the array is as follows:

 let A = [
    {name: '张三', age: 18, sex:'男'},
    {name: '李四', age: 26, sex:'男'},
    {name: '王五', age: 32, sex:'男'}
]

let B = [
    {name: '李四', age: 25, sex:'男', height: 170},
    {name: '刘六', age: 32, sex:'女'}
]

合并后:C = [{
    {name: '张三', age: 18, sex:'男'},
    {name: '李四', age: 25, sex:'男', height: 170},
    {name: '王五', age: 32, sex:'男'},
    {name: '刘六', age: 32, sex:'女'}
}]

operate

Let's analyze the A and B arrays. There are objects with name=Li Si in both A and B, so they need to be replaced, and the name=Liu Liu in B does not exist in A, so we need to add them. Without further ado, we pass js reduce method, the code is as follows:

 const C = B.reduce((arr1, arr2)=>{
        // arr1第一次进来是等于初始化化值:A
        // arr2依次是B中的对象,挨个判断
        let isFlag = false
        arr1.forEach(item => {
          if(item.name === arr2.name){
            isFlag = true
            // 如果找到则替换
            item = Object.assign(item, arr2)
          }
        })
        if(!isFlag){
          // 如果找不到则新增
          arr1.push(arr2)
        }
        // 返回结果值arr1,作为reduce下一次的数据
        return arr1
      }, A)

In this way, the A and B arrays can be successfully merged. If you don't know much about the reduce method, you can check the official documentation of mdn.


Awbeci
3.1k 声望215 粉丝

Awbeci