首页 文章

按特定分组并计算动态添加对象 Angular 2 的总计

提问于
浏览
0

我在 Angular 2 中有一个表单,其中的字段由用户动态添加。添加的对象如下所示:

[ { "equipment_type_id": 1, "action": "added", "quantity": 3}]

设备类型可以使用不同的数量重复多次,我需要按 equipment_type_id 分组并使用数量计算总数。

我已经使用 reduce 函数进行分组,但我不确定如何计算总数而不是仅仅将数量添加到新对象

var groups = this.inspection.equipments.reduce(function(obj,item){
  obj[item.equipment_type_id] = obj[item.equipment_type_id] || [];
  obj[item.equipment_type_id].push(item.quantity);
  return obj;
}, {});

任何帮助都会很棒

2 回答

  • 0

    首先,您需要检查是否已添加该类型的项目:

    if (obj[item.equipment_type_id] == null)
    

    如果它有(i.e.上面的 if 语句为 false),那么只需添加新数量:

    obj[item.equipment_type_id].quantity += item.quantity;
    

    以下是一个例子

    let equipments = [ 
      { "equipment_type_id": 1, "action": "added", "quantity": 3},
      { "equipment_type_id": 1, "action": "added", "quantity": 5},
      { "equipment_type_id": 2, "action": "added", "quantity": 4}
    ]
    
    var groups = equipments.reduce(function(obj,item) {
      if (obj[item.equipment_type_id] == null) {
        obj[item.equipment_type_id] = item;
      } else {
        obj[item.equipment_type_id].quantity += item.quantity;
      }
      return obj;
    }, {});
    
    console.log(groups);
    
  • 0

    修复此问题使用以下内容:

    calcTotals(){
        var groups = this.inspection.equipments.reduce(function(obj,item){
          obj[item.equipment_type_id] = obj[item.equipment_type_id] || { equipment_type_id: item.equipment_type_id, total: 0};
          // Calculate total based on action
          var total = obj[item.equipment_type_id].total;
          if(item.action === 'added'){
            total = total + item.quantity;
          }else{
            total = total - item.quantity;
          };
          obj[item.equipment_type_id].total = total;
          return obj;
        }, {});
        return groups;
    }
    

相关问题