js陣列物件相同項合併處理

itwangchen發表於2019-01-16
 js陣列物件相同項合併處理
平時工作中會經常遇到資料處理,其中陣列合並處理也會經常遇到,下面就是陣列相同項合併的一種方式:
- 1.首先由原始的陣列arr資料,
- 2.然後建立一個map空物件和一個dest空陣列,通過判斷map中是否含有某項來判斷陣列dest是否新增資料,
- 3.然後再判斷相同項和已有的dest陣列內容比較合併;

 var arr = [

    {"id":"1","name":"張三","value":"1245"},
    {"id":"1","name":"張三","value":"1360"},
    {"id":"2","name":"李四","value":"1120"},
    {"id":"2","name":"李四","value":"1362"},
    {"id":"2","name":"李四","value":"1008"},
    {"id":"3","name":"王五","value":"1360"},
    {"id":"4","name":"趙六","value":"1986"},
    {"id":"4","name":"趙六","value":"1240"}
  ];
  var map = {},dest = [];
  for(var i = 0; i < arr.length; i++){
    var ai = arr[i];
    if(!map[ai.id]){
      dest.push({
        id: ai.id,
        name: ai.name,
        value: ai.value
      });
      map[ai.id] = ai;
    }else{
      for(var j = 0; j < dest.length; j++){
        var dj = dest[j];
        if(dj.id == ai.id){
          dj.value=(parseFloat(dj.value) + parseFloat(ai.value)).toString();
          break;
        }
      }
    }
  };
  console.log(JSON.stringify(dest));

 結果如下

[{"id":"1","name":"張三","value":"2605"},
{"id":"2","name":"李四","value":"3490"},
{"id":"3","name":"王五","value":"1360"},
{"id":"4","name":"趙六","value":"3226"}]


相關文章