Angular-如何使用求和和分组

我需要根据ID对记录进行分组并显示权重之和。有人可以让我知道Angular中的总和和分组方法吗?

API响应:

data = [
  {Id:1, name: 'ABC', weight: 10 },
  {Id:1, name: 'ABC', weight: 14 },
  {Id:1, name: 'ABC', weight: 16 },
  {Id:2, name: 'DEF', weight: 23 },
  {Id:2, name: 'DEF', weight: 22 },
  {Id:4, name: 'GHI', weight: 44 },
  {Id:4, name: 'GHI', weight: 41 }
]

预期产量:

dataResult =  [
      {Id:1, name: 'ABC', weight: 40 },
      {Id:2, name: 'DEF', weight: 45 },
      {Id:4, name: 'GHI', weight: 85 }
    ]
评论
  • 回忆那么真
    回忆那么真 回复

    请尝试这种方法

    data = [
      {Id:1, name: 'ABC', weight: 10 },
      {Id:1, name: 'ABC', weight: 14 },
      {Id:1, name: 'ABC', weight: 16 },
      {Id:2, name: 'DEF', weight: 23 },
      {Id:2, name: 'DEF', weight: 22 },
      {Id:4, name: 'GHI', weight: 44 },
      {Id:4, name: 'GHI', weight: 41 }
    ]
    var holder = {};
    
    data.forEach(function(d) {
      if (holder.hasOwnProperty(d.name)) {
        holder[d.name] = holder[d.name] + d.weight;
      } else {
        holder[d.name] = d.weight;
      }
    });
    
    var obj2 = [];
    
    for (var prop in holder) {
      obj2.push({ name: prop, value: holder[prop] });
    }
    
    console.log(obj2)
  • son
    son 回复

    You can use Array.reduce() to iterate over and Array.find() to find item by id. Then you can calculate the sum as followings:

    const data = [
      {Id:1, name: 'ABC', weight: 10 },
      {Id:1, name: 'ABC', weight: 14 },
      {Id:1, name: 'ABC', weight: 16 },
      {Id:2, name: 'DEF', weight: 23 },
      {Id:2, name: 'DEF', weight: 22 },
      {Id:4, name: 'GHI', weight: 44 },
      {Id:4, name: 'GHI', weight: 41 }
    ]
    
    const calculated = data.reduce((acc, item) => {
      
      let accItem = acc.find(ai => ai.Id === item.Id)
      
      if(accItem){
          accItem.weight += item.weight 
      }else{
         acc.push(item)
      }
    
      return acc;
    },[])
    
    console.log(calculated)