首页 > 解决方案 > 如何计算 JSON 中为空的元素个数?

问题描述

我有一个这样的json数据:

{
    "contract_no":"1",
    "history_no":"",
    "f_sin":"",
    "line_no":"",
    "p_typeid":"3",
    "compare_typeid":1,
    "val_typeid":"1",
    "goal_val":0,
    "count_typeid":1,
    "f_pb_ignore":0,
    "all_products":0,
    "judge_typeid":"",
    "reach_condition_array":[
        {
            "up_s_line_no":1,
            "t_from":111,
            "t_to":222,
            "rebate":11
        },
        {
            "up_s_line_no":2,
            "t_from":222,
            "t_to":null,
            "rebate":22
        }
    ],
    "series_appoint":[
        {
            "down_s_line_no":1,
            "deptCD":"0",
            "categoryCD":"12",
            "singleJan":"",
            "seriesJan":"",
            "fExclude":0
        },
{
            "down_s_line_no":1,
            "deptCD":null,
            "categoryCD":"4",
            "singleJan":"",
            "seriesJan":"",
            "fExclude":0
        },
{
            "down_s_line_no":1,
            "deptCD":"55",
            "categoryCD":"",
            "singleJan":"",
            "seriesJan":"",
            "fExclude":0
        },
{
            "down_s_line_no":1,
            "deptCD":"",
            "categoryCD":2222,
            "singleJan":"58796",
            "seriesJan":"1000000009",
            "fExclude":0
        }
    ]
}

我想知道在数组“series_appoint”中,有多少“deptCD”元素是“”或 null,有多少“singleJan”是“”或 null。

在我的示例中,“deptCD”的计数为“”或 null 为 2,“singleJan”的计数为“”或 null 为 3。

标签: jqueryjson

解决方案


您可以使用Array#filter从数组中返回匹配的元素,然后计算长度。

let obj = {"contract_no":"1","history_no":"","f_sin":"","line_no":"","p_typeid":"3","compare_typeid":1,"val_typeid":"1","goal_val":0,"count_typeid":1,"f_pb_ignore":0,"all_products":0,"judge_typeid":"","reach_condition_array":[{"up_s_line_no":1,"t_from":111,"t_to":222,"rebate":11},{"up_s_line_no":2,"t_from":222,"t_to":null,"rebate":22}],"series_appoint":[{"down_s_line_no":1,"deptCD":"0","categoryCD":"12","singleJan":"","seriesJan":"","fExclude":0},{"down_s_line_no":1,"deptCD":null,"categoryCD":"4","singleJan":"","seriesJan":"","fExclude":0},{"down_s_line_no":1,"deptCD":"55","categoryCD":"","singleJan":"","seriesJan":"","fExclude":0},{"down_s_line_no":1,"deptCD":"","categoryCD":2222,"singleJan":"58796","seriesJan":"1000000009","fExclude":0}]};

function blank(value) {
  return value === null || value.trim() === '';
}

let series = obj.series_appoint;
console.log('deptCD', series.filter(item => blank(item.deptCD)).length);
console.log('singleJan', series.filter(item => blank(item.singleJan)).length);


推荐阅读