Vimalraj Selvam Vimalraj Selvam - 4 months ago 7
Javascript Question

Filter the nested array based on condition

I have an object like this:

runs =
{
"suites": [
{
"status": "fail",
"testcases": [
{
"status": "pass"
},
{
"status": "fail"
}
]
},
{
"status": "pass",
"testcases": [
{
"status": "pass"
}
]
}
]
}


I would like to retrieve the count of test case pass and fail (In the above case pass: 2, fail: 1). I tried the following to get the pass count:

runs.suites.filter(suite => {
suite.testcases.filter(testcase => {
return testcase.status === 'pass';
})
}).length


But it is giving me an incorrect result.

Answer

Try this

// Code goes here

    runs = 
        {
            "suites": [
                {
                    "status": "fail",
                    "testcases": [
                        {
                            "status": "pass"
                        },
                        {
                            "status": "fail"
                        }
                    ]
                },
                {
                    "status": "pass",
                    "testcases": [
                        {
                            "status": "pass"
                        }
                    ]
                }
            ]
        };
        var count = 0;
        var test = runs.suites.filter(suite => {
            suite.testcases.filter(testcase => {
                (testcase.status=='pass')?count++:count;
            })
            return count;
        });

    console.log(test.length);