有时候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);