arrays - 对数组中的值求和
问题描述
我试图根据它们的级别对数组中的值求和,但目前没有成功。
我正在使用的数据(命名为变量 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');*/
}
}
});
解决方案
您可以结合使用函数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);
推荐阅读
- python - 与允许您拖放图像的框相对应的 Google Image 的 id 或类是什么?
- spring - SpringBoot Actuator 不显示计划任务
- snakemake - 从snakemake将参数传递给cwl
- image - 关于如何提供用户特定图像文件的建议
- rust - 如何修复未使用的生命周期?
- reactjs - 将点击元素的信息作为道具传递给模式 - Reactjs
- python - 导入 Jupyter Notebooks 的 NotImplementedError
- html - Bootstrap 3 网格 - 图像重叠
- python - 更新 Homebrew 后如何修复丢失的库
- css - 当我点击链接时蓝色