javascriptarraysjson

Read data from arrays in JavaScript


I'm trying to read data from an array in JSON with JavaScript but I can't get it working. This is the segment of the JSON file from which I want to read the data, I want to read the age variable from different arrays:

{
    "failCount" : 1,
    "skipCount" : 15,
    "totalCount" : 156,
    "childReports" : 
    [
        {
            "result" : 
            {
                duration : 0.97834,
                empty : false,
                suites : 
                [
                    cases : 
                    [
                        {
                            "age" : 0,
                            "status" : Passed
                        }
                        {
                            "age" : 15,
                            "status" : Passed
                        }
                        {
                            "age" : 3,
                            "status" : failed
                        }
                    ]
                ]
            }
        }
    ]
}

I've tried this:

for (var i = 0; i < jsonData.childReports.suites.cases.length; i++) 
{
    var age = jsonData.childReports.suites.cases[i];
}

But it doesn't work. What would be the best way to do this?

Thanks in advance


Solution

  • Try the following code:

      for (var i = 0; i < jsonData.childReports[0].result.suites[0].cases.length; i++) {
            var age = jsonData.childReports[0].result.suites[0].cases[i].age;
        }