2015-03-31 82 views
2

我想通過Id中的數組來組織對象的數組,並按數量在Jquery中進行總和? 例如:如何在Jquery中對數組進行求和和求和?

var array=[ 
{Id:"001",qty:1}, 
{Id:"002",qty:2}, 
{Id:"001",qty:2}, 
{Id:"003",qty:4} 
] 

後,我集團是由ID我會喜歡這個新陣:

[ 
    {Id:"001",qty:3}, 
    {Id:"002",qty:2}, 
    {Id:"003",qty:4} 
    ] 

回答

10

您可以循環,概括起來

var result = []; 
array.reduce(function (res, value) { 
    if (!res[value.Id]) { 
     res[value.Id] = { 
      qty: 0, 
      Id: value.Id 
     }; 
     result.push(res[value.Id]) 
    } 
    res[value.Id].qty += value.qty 
    return res; 
}, {}); 

演示:Fiddle

+0

設置'qty'爲0是重要的在'RES [value.Id] = {數量:0,ID:value.Id};'步驟。否則,你會得到重複的值 – JustLearning 2017-05-03 08:53:23

2
var newArr = []; 

$.each(array,function(index,element){ 
    if(newArr[element.Id]==undefined){ 
     newArr[element.Id] =0; 
    } 
    newArr[element.Id] += element.qty; 
}); 
console.log(newArr); 

Demo