我有一个对象需要对其中所有嵌套的值进行求和。我的对象如下:
const json = [
{
"other_sum": "1",
"summary": {
"calculations": {
"time": 10,
"unit": 25
},
"updated": "2020-06-05"
}
},
{
"other_sum": "1",
"summary": {
"calculations": {
"time": 20,
"unit": 5
},
"updated": "2020-06-05"
}
},
{
"other_sum": "1",
"summary": {
"calculations": {
"time": 5,
"unit": 15
},
"updated": "2020-06-05"
}
},
];
我需要对所有“unit”值进行求和。
我一直在尝试使用.reduce实现这个目标,但只有当对象中有两个元素时才能正常工作,一旦我有第三个元素,就会出现错误。
我的其余代码如下:
const r = json.reduce((a, b) => a.summary.calculations.unit + b.summary.calculations.unit);
console.log(r);
目前我不太确定自己哪里出了问题。
reduce
提供起始值(在调用时它是第二个参数,在这里应该是零)。 - Touffya
不需要summary.calc.unit
这些东西,它只是一个数字。json.reduce((a, e) => a + e.summary.calculations.unit, 0)
。欢迎来到SO! - ggorlentypeof ArrayInstance === 'object'
,但是ArrayInstance instanceof Array
。我知道你知道这一点,但OP可能不知道。只是一个评论来纠正你说它不是一个对象的说法,因为数组是一个对象。 - StackSlave