Is there a more elegant way to iterate over json array in js?

I am trying to iterate over a json array and calculate number of hours from every object. The code works but it just feels like there could be a more efficient way to write the code, but whatever I try the code just breaks.

My json array:

{
    "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
        }
    ]
}

Iteration:

let numberOfSheets = 0;
const lam = this.state.sheets.forEach( item => numberOfSheets += item.hours)

1 thought on “Is there a more elegant way to iterate over json array in js?”

  1. Try using reduce on the timesheetItems array:

    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);
    Reply

Leave a Comment