jquery - 如何计算 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。
解决方案
您可以使用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);
推荐阅读
- java - 我正在尝试将内容作为字符串放入 ListView
- windows - 无法再使用 vsjitdebugger 在启动时调试进程
- class - Java将具有逗号分隔值的字符串列表转换为对象列表
- c++ - 标头保护文件中结构的重复符号
- java - 如何通过按键和释放来开始和结束循环?
- javascript - 为什么 curl 在收到早期响应时会提前终止对我的服务器的 http 请求,但来自我的浏览器前端的 http 请求却没有?
- c++ - 在特定内存位置构造 c++ 对象
- spring-boot - 创建名为“jpaMappingContext”的 bean 时出错
- python - 覆盖cmd Python模块完成功能
- c# - 在 NSubstitute 中构造带有抛出异常的 void 方法的调用序列