Screen the embedded array depending on the criteria

Here is an example of an object I have:

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

I am trying to determine the count of test cases that have passed and failed (In this case pass: 2, fail: 1). I attempted the following code to get the pass count:

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

Unfortunately, the result is not what I expected.

Answer №1

Here is a code snippet for you to try:

// Check out this code snippet

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

Answer №2

An effective way to keep track of occurrences is by utilizing an object for counting purposes.

var occurrences = { "categories": [{ "type": "apple", "quantity": 5 }, { "type": "orange", "quantity": 3 }] },
count = {}

occurrences.categories.forEach(category => 
    count[category.type] = (count[category.type] || 0) + category.quantity);

console.log(count);

Answer №3

Give this a shot:

let testResults = {"runs": [{"outcome": "failed","tests": [{"outcome": "passed"},{"outcome": "failed"}]},{"outcome": "passed","tests": [{"outcome": "passed"}]}]};
const outcomes = testResults.runs.reduce((a, b)=> a.tests.concat(b.tests)).map(x=> x.outcome);
console.log(outcomes.filter(x=> x === "passed").length) // 2
console.log(outcomes.filter(x=> x === "failed").length) // 1

Answer №4

To effectively count the number of pass and fail occurrences, you can utilize the Array#reduce method and store the results in an object like this: {pass: 2, fail: 1}

var testRuns = {"suites": [{"status": "fail","testcases": [{"status": "pass"},{"status": "fail"}]},{"status": "pass","testcases": [{"status": "pass"}]}]};

var results = testRuns.suites.reduce( (accumulator, current)=> {
  current.testcases.forEach(testCase=>{
    testCase.status === 'pass' ? accumulator.pass++ : accumulator.fail++;
  });
  return accumulator;
}, {pass: 0, fail: 0});

console.log(results);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it really necessary to still think poorly of JavaScript in 2011?

Here's an intriguing question for you. I've tested out a variety of popular websites, including Facebook, and I've noticed that many features still work perfectly fine even when JavaScript is disabled. People always used to say that JavaScr ...

Can you clarify the concept of closures and how they bind the loop counter to the function scope?

I have observed programmers setting up event listeners inside loops, utilizing the counter. The syntax that I have come across is as follows: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); ...

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

React error: Updating state is only allowed on mounted or mounting components

I'm encountering this Error/Warning message in my console: The error message says: setState(...): Can only update a mounted or mounting component. Addressing the Component Mounting Process When it comes to mounting the component, here's the r ...

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Ways to Implement an Origin's First-Party Cookies While Using it as a Third-Party

Imagine I am the owner of a website called "treat1creator.com". I want my clients, who are also website owners, to send HTTP requests to my server that contain cookies I have generated. Here is how it works: User "Sally" visits my site at treat1creator.co ...

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

Scrolling automatically to a DIV is possible with jQuery, however, this feature is functional only on the initial

I'm currently working on a Quiz site and I've encountered a puzzling issue. Since the explanation only appears after an answer is selected - essentially a "hidden" element, I decided to wrap that explanation into a visible DIV. The code I'v ...

Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be dis ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

The autofocus feature on the textarea in Angular Material Dialog seems to be malfunctioning

Within a web app, I am utilizing the Dialog component from Angular Material. The Dialog consists of only a textarea that is initially empty. I aim to automatically focus on the textarea when the user opens the modal dialog. How can I achieve this? Despite ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

Add an image to a div element and determine its height, then apply the height to the CSS property

Here is my JavaScript code that utilizes jQuery: $(".article_big_photo").click(function() { $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); $('#screen').show() ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Adding an image to a jQuery class name on the fly

I am attempting to add an image before a div by using its className with jQuery. function insertImage(obj) { var dynamicClass = $(obj).prop("className"); After retrieving the classname, I now encapsulate it in single quotes and add a dot to access t ...

Retrieve the jsonb value from a json structure that includes a json array in PostgreSQL

I am working with a JSON column that contains data like the following: {"image_pose_array": [{"image_name": "0026568143_WS.jpg", "image_pose": "EXTRA", "is_blurred": false, "is_dark": fal ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

What is the process for sending Raw Commands to a Receipt Printer using Node.JS?

My Current Project I am currently working on integrating a receipt printer that supports ESC/P raw printing into an app for remote printing of receipts. The Approach I Am Taking To achieve this, I am utilizing the PrintNodes API to send data from my app ...

Discovering the earliest and latest dates within an array of date strings

My data consists of an array filled with objects like this data = [ { mas_name: (...), mas_plan_end: (...) // 'YYYY-MM-DD' eg: '2021-03-19' mas_plan_start: (...) // 'YYYY-MM-DD' eg: '2021-03-19' ... }, { ...