根据条件过滤嵌套数组

时间:2016-07-11 11:17:02

标签: javascript arrays ecmascript-6

我有一个这样的对象:

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

我想检索测试用例传递和失败的计数(在上面的情况下传递:2,失败:1)。我尝试了以下方法来获取通过次数:

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

但它给了我一个不正确的结果。

4 个答案:

答案 0 :(得分:1)

试试这个:

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

const statuses = runs.suites.reduce((a, b)=> a.testcases.concat(b.testcases)).map(x=> x.status)
console.log(statuses.filter(x=> x === "pass").length) // 2
console.log(statuses.filter(x=> x === "fail").length) // 1

答案 1 :(得分:1)

您可以使用对象进行计数。

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

runs.suites.forEach(a => 
    a.testcases.forEach(b =>
        count[b.status] = (count[b.status] || 0) + 1));

console.log(count);

答案 2 :(得分:1)

试试这个

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

答案 3 :(得分:0)

您可以使用Array#reduce并计算对象{pass : 2, fail : 1}

中的通过/失败计数



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

var obj = runs.suites.reduce( (tot, curr)=> {
  curr.testcases.forEach(tc=>{
    tc.status === 'pass' ? tot.pass++ : tot.fail++;
  });
  return tot;
}, {pass : 0, fail : 0});

console.log(obj);