Sum the same object of array

前端 未结 4 705
[愿得一人]
[愿得一人] 2021-01-25 09:09
var data = [ {id:1, qty:100}, {id:2, qty:200}, {id:1, qty:100}, {id:2, qty:200} ];

How to sum this array become to [ {id:1, qty:200}, {id:2, qty:

4条回答
  •  清歌不尽
    2021-01-25 09:43

    I didn't get to run this on any data, but the logic seems right. Basically this code goes through your array, and for each unique instance it will store the values into a temporary array and the write over the original array with the results.

    var temp = [];
    temp.push(data[0])
    for (x = 1; x < data.length; x++){
      for (i = 0; i < temp.length; i++){
        if (temp[i].id != data[x].id && temp[i].qty != data[x].qty ){
          temp.push[data[x]];
        }
      }
    }
    data = temp;
    

提交回复
热议问题