首页 > 解决方案 > 对数组中的值求和

问题描述

我试图根据它们的级别对数​​组中的值求和,但目前没有成功。

我正在使用的数据(命名为变量 totalByLevel ):

在此处输入图像描述

我想要的是 :

将每个级别的每个总数放在 1 个数组中,例如:['total of 3 + 4', 'total of 6 + 7', etc...]

我尝试了什么:

我试图创建一个空数组并将 3 + 4 中的值推送到数组中,这是有效的,但不是有意的。

在此处输入图像描述

只有最后一个值保留在数组中,所有其他值都被删除,如果您有修复它,我将非常感谢任何帮助!先感谢您。

组件.ts

for (const levelKey in this.totalByLevel ) {
        if (this.totalByLevel .hasOwnProperty(levelKey)) {
          const key = this.labelName[levelKey];
          const value = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[0]];
          const value2 = this.labelName[Object.keys(this.totalByLevel [levelKey])[0]];
          const value3 = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[1]];
          const value4 = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[2]];

          this.output_object[key] = value;
          this.output_object2[key] =  value2;
          const sum = [];
          if (value4 !== undefined || null) {
            sum.push((+value + +value3 + +value4).toFixed(2));
            console.log(sum, 'SUM 3');
            this.totalPerCat = sum;

          } else if (value4 === undefined || null) {
             sum.push((+value + +value3).toFixed(2));
             console.log(sum, 'SUM 2');
             this.totalPerCat = sum;

          } else if (value3 === undefined || null) {
            sum.push(value);
            console.log(sum, 'SUM 1');
            this.totalPerCat = sum;

          }
          console.log(this.totalPerCat);
/*          console.log(value3);
          console.log(value4);
          console.log(+value + +value3 + +value4, 'SUM');*/
        }
      }
    });

标签: arraysangulartypescript

解决方案


您可以结合使用函数Object.values()和数组reduce。尝试以下

var totalByLevel = {
  2: {
    3: '3514.80',
    4: '7259.32'
  },
  5: {
    6: '864941.86',
    7: '1076976.54'
  }
};

var sum = Object.values(totalByLevel).reduce((acc, curr) => {
  acc.push(String(Object.values(curr).reduce((a, c) => a + Number(c), 0)));
  return acc;
}, []);

console.log(sum);


推荐阅读