简体   繁体   English

JS Reduce返回数组中的第一项为null

[英]JS Reduce first item in returned array is null

Hi I am using the following function to group by a key and calculate a total: 嗨,我正在使用以下功能按键分组并计算总数:

calcEquipmentTotals(){
    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' || item.action === 'stocktake'){
        total = total + item.quantity;
      }else{
        total = total - item.quantity;
      };
      obj[item.equipment_type_id].total = total;
      return obj;
    },[]);
    return groups;
  }

This is working great except the first item is an empty object, what am I doing wrong here? 除了第一个项目是一个空对象外,这工作得很好,我在这里做错了什么?

[ null, { "equipment_type_id": 1, "total": 1 }, { "equipment_type_id": "2", "total": 10 } ]

This will do what you want. 这将做您想要的。

 calcEquipmentTotals() {
  var groups = this.inspection.equipments.reduce(function (map, item) {

    const obj = map.get(item.equipment_type_id) || {
      equipment_type_id: item.equipment_type_id, total: 0
    };

    if (item.action === 'added' || item.action === 'stocktake') {
      obj.total += item.quantity;
    } else {
      obj.total -= item.quantity;
    };
    map.set(obj);

    return map;
  }, new Map());
  return Array.from(groups.values());
}

The comments pointed me in the right direction, this is what got it done in the end: 这些评论为我指明了正确的方向,这是最终完成的工作:

calcEquipmentTotals(){
    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' || item.action === 'stocktake'){
        total = total + item.quantity;
      }else{
        total = total - item.quantity;
      };
      obj[item.equipment_type_id].total = total;
      return obj;
    },{});
    return Object.keys(groups).map((key) => groups[key]);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM