js compares the old and new arrays, extracts, adds, modifies, and deletes arrays

1. Usage scenarios

1. Compare the old and new arrays to extract the increased and decreased element data;

2. In the actual project, when the front desk sends data in array format to the background, it can first compare the new and old data, and only send the changed added data and deleted data to the background each time to increase the transmission efficiency;

Second, without further ado, let's look at the code directly

1. Multi-condition extraction increases and modifies arrays

Here, the key-value pair relationship of map is mainly used to reduce the time complexity. Use two field attributes as the primary key to judge whether the new and old data are the same. You may use a primary key to judge whether you use it. You can modify the code accordingly, and do not use **JSON.stringify()** to convert the string as the only one. primary key.

<!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 = [{
    
    
                sysDocKindId: 1,
                attachType: 2,
                str: 'del的'
            },
            {
    
    
                sysDocKindId: 3,
                attachType: 2,
            },
            {
    
    
                bid: 1,
                attachType: 1,
            },
            {
    
    
                bid: 8,
                attachType: 1,
                str: 'del的'
            },
            {
    
    
                sysDocKindId: 5,
                attachType: 2,
            },
            {
    
    
                bid: 6,
                attachType: 1,
            },
            {
    
    
                sysDocKindId: 6,
                attachType: 2,
            },
        ]
        let arr2 = [{
    
    
                sysDocKindId: 3,
                attachType: 2,
            },
            {
    
    
                bid: 1,
                attachType: 1,
            },
            {
    
    
                sysDocKindId: 5,
                attachType: 2,
            },
            {
    
    
                bid: 6,
                attachType: 1,
            },
            {
    
    
                sysDocKindId: 6,
                attachType: 2,
            },
            {
    
    
                sysDocKindId: 9,
                attachType: 2,
                str: 'add的'
            },
            {
    
    
                bid: 9,
                attachType: 1,
                str: 'add的'
            },
        ]
        /**
         * 方法名:
         * 功能介绍:返回一个对象里面包含后一个数组比第一个数组增加、减少的数据(适用于去重过后的数组)
         * 参数:
         * beforeArr:前一个数组
         * afterArr:后一个数组
         */
        const compare = (beforeArr, afterArr) => {
    
    
            let resObj = {
    
    
                add: [],
                del: []
            }
            let cenMab = new Map();
            //把beforeArr数组去重放入cenObj 
            for (let i = 0; i < beforeArr.length; i++) {
    
    
                if (beforeArr[i].attachType === 2) {
    
    
                    cenMab.set(JSON.stringify({
    
    
                        sysDocKindId: beforeArr[i].sysDocKindId,
                        attachType: beforeArr[i].attachType,
                    }), beforeArr[i])
                } else {
    
    
                    cenMab.set(JSON.stringify({
    
    
                        bid: beforeArr[i].bid,
                        attachType: beforeArr[i].attachType,
                    }), beforeArr[i])
                }
            }
            //遍历afterArr,查看其元素是否在cenObj中
            for (let j = 0; j < afterArr.length; j++) {
    
    
                let typeOne = JSON.stringify({
    
    
                    sysDocKindId: afterArr[j].sysDocKindId,
                    attachType: afterArr[j].attachType,
                })
                let typeTwo = JSON.stringify({
    
    
                    bid: afterArr[j].bid,
                    attachType: afterArr[j].attachType,
                })
                if (cenMab.has(typeOne) || cenMab.has(typeTwo)) {
    
    
                    let r1 = cenMab.delete(typeOne)
                    let r2 = cenMab.delete(typeTwo)

                } else {
    
    
                    resObj.add.push(afterArr[j]);

                }
            }
            for (let item of cenMab.values()) {
    
    
                resObj.del.push(item);
            }
            return resObj
        }
        console.log(compare(arr1, arr2));;
    </script>
</body>

</html>

2. Extract, add, modify, and delete arrays

let arr1 = [{
    
    
                id: 1,
                sysAuthObjTypeId: 1,
                sysAuthDefId: 2,
                actionTag: 17,
                str: '删除的'
            },
            {
    
    
                id: 2,
                sysAuthObjTypeId: 3,
                sysAuthDefId: 2,
                actionTag: 17,
            },
            {
    
    
                id: 3,
                sysAuthObjTypeId: 1,
                sysAuthDefId: 1,
                actionTag: 17,
                str: '没变的'
            },
            {
    
    
                id: 4,
                sysAuthObjTypeId: 8,
                sysAuthDefId: 1,
                actionTag: 17,
                str: '删除的'
            },
            {
    
    
                id: 5,
                sysAuthObjTypeId: 5,
                sysAuthDefId: 2,
                actionTag: 17,
            },
            {
    
    
                id: 6,
                sysAuthObjTypeId: 6,
                sysAuthDefId: 1,
                actionTag: 17,
                str: '没变的'
            },
            {
    
    
                id: 7,
                sysAuthObjTypeId: 6,
                sysAuthDefId: 2,
                actionTag: 17,
            },
        ]
        let arr2 = [{
    
    
                sysAuthObjTypeId: 3,
                sysAuthDefId: 2,
                actionTag: 17,
                str: '删除后又添加权限值 没变的'
            },
            {
    
    
                id: 3,
                sysAuthObjTypeId: 1,
                sysAuthDefId: 1,
                actionTag: 17,
                str: '没变的'
            },
            {
    
    
                id: 5,
                sysAuthObjTypeId: 5,
                sysAuthDefId: 2,
                actionTag: 1,
                str: '变的'
            },
            {
    
    
                sysAuthObjTypeId: 6,
                sysAuthDefId: 1,
                actionTag: 17,
                str: '删除后又添加权限值 没变的'
            },
            {
    
    
                sysAuthObjTypeId: 6,
                sysAuthDefId: 2,
                actionTag: 16,
                str: '删除后又添加权限值 变的'
            },
            {
    
    
                sysAuthObjTypeId: 9,
                sysAuthDefId: 2,
                actionTag: 3,
                str: 'add的'
            },
            {
    
    
                sysAuthObjTypeId: 9,
                sysAuthDefId: 1,
                actionTag: 3,
                str: 'add的'
            },
        ]
        /**
         * 方法名:
         * 功能介绍:返回一个对象里面包含后一个数组比第一个数组增加、减少的数据(适用于去重过后的数组)
         * 参数:
         * beforeArr:前一个数组
         * afterArr:后一个数组
         */
        const compare = (beforeArr, afterArr) => {
    
    
            let resObj = {
    
    
                insertList: [],
                deleteList: [],
                updateList: [],
                isChange: false,
            };

            let cenMab = new Map();
            //把beforeArr数组去重放入cenObj 
            for (let i = 0; i < beforeArr.length; i++) {
    
    
                cenMab.set(JSON.stringify({
    
    
                    sysAuthObjTypeId: beforeArr[i].sysAuthObjTypeId,
                    sysAuthDefId: beforeArr[i].sysAuthDefId,
                }), beforeArr[i])
            }
            //遍历afterArr,查看其元素是否在cenObj中
            for (let j = 0; j < afterArr.length; j++) {
    
    
                let typeOne = JSON.stringify({
    
    
                    sysAuthObjTypeId: afterArr[j].sysAuthObjTypeId,
                    sysAuthDefId: afterArr[j].sysAuthDefId,
                })
                if (cenMab.has(typeOne)) {
    
    
                    console.log(afterArr[j].actionTag );
                    if (cenMab.get(typeOne).actionTag != afterArr[j].actionTag) {
    
    
                        resObj.isChange = true;
                        resObj.updateList.push({
    
    
                            ...afterArr[j],
                            id: cenMab.get(typeOne).id
                        });
                    }
                    let r1 = cenMab.delete(typeOne)
                } else {
    
    
                    resObj.isChange = true;
                    resObj.insertList.push(afterArr[j]);
                }
            }
            // 遍历push剩余删除的数据
            for (let item of cenMab.values()) {
    
    
                resObj.isChange = true;
                resObj.deleteList.push(item);
            }
            return resObj
        }
        console.log(compare(arr1, arr2));

3. Running results:

It can be seen that the data that needs to be added and added are extracted into the add and del arrays respectively, and you can encapsulate the function call yourself when using it.

operation result

Guess you like

Origin blog.csdn.net/weixin_44982333/article/details/127566177