1. 程式人生 > 實用技巧 >json陣列去重

json陣列去重

json陣列去重函式

//json去重函式
//1、傳入json或陣列
//2、傳入去重的鍵名
function abs(arr,key_name){
    var new_arr = [];
    var i = 0;
    for(key in arr){
        var key_name_value = arr[key][key_name];
        var is_key_name_value = false;
        for(key1 in arr){
            if(key>key1 && key_name_value==arr[key1][key_name]){
                is_key_name_value 
= true; break; } } if(is_key_name_value===false){ new_arr[i] = arr[key]; i++; } } return new_arr; } //定義json var a = [{user_id: "WV00000002", user_name: "王維", work_date: "2020-08-06", class_id: 9, classes_name: "顏色測試"}, {user_id:
"WV00000002", user_name: "王維", work_date: "2020-08-14", class_id: 1, classes_name: "早班"} ,{user_id: "WV00000004", user_name: "張穎", work_date: "2020-08-09", class_id: 9, classes_name: "顏色測試"},{user_id: "WV00000005", user_name: "王發通", work_date: "2020-08-15", class_id: 9, classes_name: "顏色測試"},{user_id: "WV00000007", user_name: "宋葉飛", work_date: "2020-08-06", class_id: 9, classes_name: "顏色測試"}];
//呼叫json去重 var result = abs(a,'class_id'); //列印json console.log(result);