gpt4 book ai didi

javascript - 尝试在对象上使用 .reduce

转载 作者:行者123 更新时间:2023-12-01 15:20:52 25 4
gpt4 key购买 nike

所以我有一个对象,我需要为所有对象求和一个嵌套值。我的对象看起来像

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"
}
},
];
我需要总结所有“单位”值
我一直在尝试为此使用 .reduce ,但它仅在我的对象中有 2 个项目时才有效,一旦我得到第 3 个项目,我就会出错。
我的其余代码如下:
const r = json.reduce((a, b) => a.summary.calculations.unit + b.summary.calculations.unit);
console.log(r);
不太确定我在做什么错atm。

最佳答案

因为那不是方式reduce作品。取自 this article它是这样工作的:

Given

arrSum = function(arr){
return arr.reduce(function(a,b){
return a + b
}, 0);
}

The function that we pass as the first parameter of the reduce methodreceives two parameters, a and b. In this code, a is our accumulator.It will accumulate our sum as our function works. b is the currentvalue being processed.


所以基本上你试图访问累加器中的“摘要”,这只是一个数字。这是工作片段:

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"
}
},
];

const r = json.reduce((a, b) => a + b.summary.calculations.unit, 0);
console.log(r);

关于javascript - 尝试在对象上使用 .reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62884379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com