JS 兩個對象數組合並並去重

JS兩個對象數組合並並去重javascript

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
    </body>
</html>
<script type="text/javascript">
    let jsonArr = [
        {
            "ID": "",
            "NO": "1",
            "NAME": "測試對象1"
        },
        {
            "ID": "",
            "NO": "2",
            "NAME": "測試對象2"
        },
        {
            "ID": "",
            "NO": "3",
            "NAME": "測試對象3"
        },
        {
            "ID": "",
            "NO": "4",
            "NAME": "測試對象4"
        },
        {
            "ID": "",
            "NO": "5",
            "NAME": "測試對象5"
        }
        ];

        let jsonArr2 = [
        {
            "ID": "",
            "NO": "3",
            "NAME": "測試對象3"
        },
        {
            "ID": "",
            "NO": "4",
            "NAME": "測試對象4"
        },
        {
            "ID": "",
            "NO": "6",
            "NAME": "測試對象6"
        },
        {
            "ID": "",
            "NO": "7",
            "NAME": "測試對象7"
        }
        ];

        let length1 = jsonArr.length;
        let length2 = jsonArr2.length;
        for (let i = 0; i < length1; i++) {
            for (let j = 0; j < length2; j++) 
            {
                //判斷添加的數組是否爲空了
                if (jsonArr.length > 0) {
                    if (jsonArr[i]["NAME"] === jsonArr2[j]["NAME"]) {
                        jsonArr.splice(i, 1); //利用splice函數刪除元素,從第i個位置,截取長度爲1的元素
                        length1--; 
                        console.log(jsonArr2[j]);//重複元素
                    }
                }
            }

        } 
        
        for (let n = 0; n < jsonArr2.length; n++) {
            jsonArr.push(jsonArr2[n]);
        }

        console.log(JSON.stringify(jsonArr)); 
</script>
 
相關文章
相關標籤/搜索