由id数组求和的多维数

时间:2018-06-04 08:24:40

标签: javascript jquery

我用这种格式创建了

var = items = [];
$('#ClientList ul.list-items li').each(function () {
   items.push({
      id: $(this).attr('data-id'),
      name: $(this).attr('data-name'),
      price: $(this).attr('data-price'),
      amount: $(this).attr('data-amount')
    });
});

如果amount相同,我想添加id,因为有多个ul.list-items li,并根据客户的需要添加了项目。

1 个答案:

答案 0 :(得分:1)

您应该使用此代码通过id数组获取总和

var items =
[ 
  { id: 1 , amount : 20},
  { id: 1 , amount : 30},
  { id: 2 , amount : 10},
  { id: 2,  amount : 15},
  { id: 3,  amount : 15}
];

var results = items.reduce(function(results, item) {
    (results[item.id] = results[item.id] || []).push(item);
    return results;
}, {});

let sumByIdList =[];

Object.keys(results).forEach(function(key) {
  let sum =results[key].reduce((a, b) => a + b.amount, 0);
  sumByIdList.push({id: key , sum : sum});   
});

console.log(sumByIdList);