Loadash组并汇总多列

时间:2019-11-15 03:12:18

标签: javascript lodash

在我的Vue应用中,我需要按日期对数组进行分组,然后对多列求和。我可以这样对1列进行分组和求和:

receiptsByDate: function(){
   let byDate = _.groupBy(this.receipts, 'date');
   let totals = {};
   _.forEach(byDate, function(amounts, Date){
   totals[Date] = _.reduce( byDate[Date], function(sum, receipt){
   return sum + parseFloat( receipt.total );
   }, 0);
   })
   return totals;   
}

创建对象日期:总计。

这是应用该功能的收据示例:

card_commission:null
created_at:"2019-11-14 06:13:20"
customer_id:null
date:"2019-11-14"
discount:"12000.0"
id:1
location_id:null
number:"2019-00001"
service:null
subtotal:"200000.0"
table_id:null
taxes:null
ticket_id:1
total:"188000.0"
updated_at:"2019-11-14 06:13:20"

我需要按日期分组,但是在receiving.total旁边,我需要对其他列进行汇总,例如折扣,小计等。我没有在网上找到任何东西可以实现这一目标。任何人都可以指出正确的方向吗?不必使用loadash,也可以使用另一种方法。

2 个答案:

答案 0 :(得分:0)

您可以返回一个由每个日期的所有计算值组成的对象,而不是仅返回总计。

receiptsByDate: function(){
  let byDate = _.groupBy(this.receipts, 'date');

  let computedData = {};
  _.forEach(byDate, function(receiptList, date){
    computedData[date] = {
      total: _.sumBy(receiptList, function(receipt) {
        return parseFloat(receipt.total);
      }),
      discount: _.sumBy(receiptList, function(receipt) {
        return parseFloat(receipt.discount);
      })
    }
  };

  return computedData;
}

答案 1 :(得分:0)

更改为另一个forEach。如果您想使用日期作为键,那么

let sumary = {}
_.forEach(byDate[Date], (receipt) => {
   if(sumary.total == null)
      sumary.total = parseFloat(receipt.total)
   else
      sumary.total += parseFloat(receipt.total)

   if(sumary.other== null)
      sumary.other= parseFloat(receipt.other)
   else
      sumary.other+= parseFloat(receipt.other)
}
totals[Date] = summary

如果这是您想要的,那么您可以改进代码,只需将0替换为{total:0,other:0},然后在reduce函数中进行计算。