【问题标题】:Is there a more elegant way to iterate over json array in js?有没有更优雅的方式来遍历 js 中的 json 数组?
【发布时间】: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


【解决方案1】:

尝试在timesheetItems 数组上使用reduce

var sheets = {
    "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 = sheets.timesheetItems.reduce((numberOfSheets, item) => numberOfSheets + item.hours, 0);

console.log(numberOfSheets);

【讨论】:

  • 请记住,以上仅为示例。您需要根据自己的代码对其进行调整(例如,将 sheets 替换为 this.state.sheets)。
猜你喜欢
  • 1970-01-01
  • 2014-11-03
  • 2020-01-09
  • 2021-11-12
  • 2020-02-11
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 2016-01-23
相关资源
最近更新 更多