【发布时间】:2021-02-16 08:44:16
【问题描述】:
我正在尝试遍历 json 数组并计算每个对象的小时数。代码可以工作,但感觉可能有一种更有效的方式来编写代码,但无论我尝试什么,代码都会中断。
我的 json 数组:
{
"timesheetItems":[
{
"id":"1",
"title":"Ticket system integration",
"hours":2
},
{
"id":"2",
"title":"Integration with Google Maps API",
"hours":3
},
{
"id":"3",
"title":"Prepare test cases",
"hours":4
}
]
}
迭代:
let numberOfSheets = 0;
const lam = this.state.sheets.forEach( item => numberOfSheets += item.hours)
【问题讨论】:
-
试试
this.state.sheets.reduce((total, { hours }) => total + hours, 0)
标签: javascript arrays iteration