比较两个数组对象,取出增删改项

比较两个新旧数组对象,找出新增项、修改项和删除项

步骤

  1. 创建映射:首先为每个数组创建一个映射(对象或Map),键为对象的唯一标识,值为对象本身。
  2. 识别删除项:遍历第一个数组的映射,查找不在第二个数组映射中的项。
  3. 识别增加项:遍历第二个数组的映射,查找不在第一个数组映射中的项。
  4. 识别修改项:对于两个映射中都存在的键,比较其对应的对象是否相同。如果不同,则视为修改项。

代码实现

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      let arr1 = [
        { id: 1, table: 1, file: 1 },
        { id: 2, table: 2, file: 2 },
        { id: 3, table: 3, file: 3 },
        { id: 4, table: 4, file: 4 },
        { id: 5, table: 5, file: 5 },
        { id: 6, table: 6, file: 6 },
        { id: 7, table: 7, file: 7 },
      ]
      let arr2 = [
        { id: 1, table: 1, file: 1 },
        { id: 2, table: 2, file: 2 },
        { id: 3, table: 3, file: 3 },
        { id: 4, table: 4, file: 4 },
        { id: 5, table: 5, file: 5 },
        { id: 6, table: 6, file: 5 },
        { table: 8, file: 8 },
      ]
      const compareArrays = (beforeArr, afterArr, idKey = 'id') => {
        const resObj = {
          insertList: [],
          deleteList: [],
          updateList: [],
          isChange: false,
        };
        const map1 = new Map(beforeArr.map(item => [item[idKey], item]));
        const map2 = new Map(afterArr.map(item => [item[idKey] || item, item]));

        // 识别删除项
        resObj.deleteList = Array.from(map1).filter(([key]) => !map2.has(key)).map(([key, value]) => value);
        // 识别增加项
        resObj.insertList = Array.from(map2).filter(([key]) => !map1.has(key)).map(([key, value]) => value);
        // 识别修改项
        resObj.updateList = Array.from(map1)
          .filter(([key]) => map2.has(key))
          .filter(([key, value]) => !isEqual(value, map2.get(key)))
          .map(([key, value]) => map2.get(key));
            
        function isEqual(obj1, obj2) {
          return obj1.table === obj2.table && obj1.file === obj2.file;
        }

        if (resObj.insertList.length > 0 || resObj.deleteList.length > 0 || resObj.updateList.length > 0) {
          resObj.isChange = true;
        }

        return resObj
      }
      console.log(compareArrays(arr1, arr2));
    </script>
  </body>
</html>

输出结果

{
    "insertList": [
        {
            "table": 8,
            "file": 8
        }
    ],
    "deleteList": [
        {
            "id": 7,
            "table": 7,
            "file": 7
        }
    ],
    "updateList": [
        {
            "id": 6,
            "table": 6,
            "file": 5
        }
    ],
    "isChange": true
}
  • 23
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值