首页 > 解决方案 > Javascript - 总计并删除对象数组中的重复行

问题描述

我有一组包含一些信息的对象。颜色和大小相同的线,我想求和并删除重复的线,即对于每个颜色和大小相等的,我只想得到一条线。

我的对象数组

  data = [
{
  tam: 'S',
  color: 'blue',
  total: 5
},
{
  tam: 'S',
  color: 'blue',
  total: 10
},
{
  tam: 'S',
  color: 'blue',
  total: 20
},
{
  tam: 'M',
  color: 'blue',
  total: 5
},
{
  tam: 'L',
  color: 'blue',
  total: 5
}

];

所需的输出

 data = [
    {
      tam: 'S',
      color: 'blue',
      total: 35
    },
    {
      tam: 'M',
      color: 'blue',
      total: 5
    },
    {
      tam: 'L',
      color: 'blue',
      total: 5
    }
  ];

演示

标签: javascriptangulartypescript

解决方案


您可以使用reduce函数来汇总具有相同tam属性的元素。然后是一个map创建对象数组的结果:

data = [
    {
      tam: 'S',
      color: 'blue',
      total: 5
    },
    {
      tam: 'S',
      color: 'blue',
      total: 10
    },
    {
      tam: 'S',
      color: 'blue',
      total: 20
    },
    {
      tam: 'M',
      color: 'blue',
      total: 5
    },
    {
      tam: 'L',
      color: 'blue',
      total: 5
    }
    ];

    var result = data.reduce(function(acc, x) {
      var id = acc[x.tam]
      if (id) {
        id.tam = x.tam
        id.total += x.total
      } else {
        acc[x.tam] = x
      }
      return acc
    },{});
    
    result = Object.keys(result)
    .sort(function(x, y){return +x - +y})
    .map(function(k){return result[k]})

    console.log(result)


推荐阅读