Home > Web Front-end > JS Tutorial > JS operation JSON array deduplication

JS operation JSON array deduplication

php中世界最好的语言
Release: 2018-06-08 14:47:20
Original
2330 people have browsed it

This time I will bring you some precautions when operating JSON arrays with JS. The following is a practical case. Let’s take a look.

Requirement description: Remove items with the same paymode field in the JSON array and accumulate paymoney.

paylist:[{paymode:'1',payname:"现金",paymoney:"20"},
{paymode:'2',payname:"支付宝",paymoney:"50"},{paymode:'1',payname:"现金",paymoney:"40"}]
Copy after login
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;
}
Copy after login

General JSON array deduplication

/*
 * 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;
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

React props and state attribute practical case explanation

File encoding base64 upload through AJAX

The above is the detailed content of JS operation JSON array deduplication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template