这次给大家带来JS如何实现JSON数组内的去重算法,JS实现JSON数组的重算法的注意事项有哪些,下面就是实战案例,一起来看一下。
需求描述:去除JSON数组中paymode字段相同的项,并将paymoney累加。paylist:[{paymode:'1',payname:"现金",paymoney:"20"},
{paymode:'2',payname:"支付宝",paymoney:"50"},{paymode:'1',payname:"现金",paymoney:"40"}]function UniquePay(paylist){
var payArr = [paylist[0]];
for(var i = 1; i < paylist.length; i++){
var payItem = paylist[i];
var repeat = false;
for (var j = 0; j < payArr.length; j++) {
if (payItem.paymode == payArr[j].paymode) {
payArr[j].paymoney = parseFloat(payArr[j].paymoney)+parseFloat(payItem.paymoney);
repeat = true;
break;
}
}
if (!repeat) {
payArr.push(payItem);
}
}
return payArr;
}
通用的JSON数组去重/*
* JSON数组去重
* @param: [array] json Array
* @param: [string] 唯一的key名,根据此键名进行去重
*/
function uniqueArray(array, key){
var result = [array[0]];
for(var i = 1; i < array.length; i++){
var item = array[i];
var repeat = false;
for (var j = 0; j < result.length; j++) {
if (item[key] == result[j][key]) {
repeat = true;
break;
}
}
if (!repeat) {
result.push(item);
}
}
return result;
}
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读: