比较两个新旧数组对象,找出新增项、修改项和删除项
步骤
- 创建映射:首先为每个数组创建一个映射(对象或Map),键为对象的唯一标识,值为对象本身。
- 识别删除项:遍历第一个数组的映射,查找不在第二个数组映射中的项。
- 识别增加项:遍历第二个数组的映射,查找不在第一个数组映射中的项。
- 识别修改项:对于两个映射中都存在的键,比较其对应的对象是否相同。如果不同,则视为修改项。
代码实现
<!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
}