检查JSON数组是否为空 [英] Check if a JSON array is empty

查看:124
本文介绍了检查JSON数组是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从第一次看起来就知道它听起来像重复的问题,但我认为不是......

I know from the first look it sounds like duplicate question but i don't think it is...

我收到一个JSON数组:

I am receiving back a JSON array as:

var test1 = [] ;

var test2 = [{},{},{}] ;  //This is empty

我可以找到 test1 为空。

jQuery.isEmptyObject(test1)

我的问题是 test2 ...
请注意,在某些情况下, test2可能会返回如下内容:

My problem is with the test2... Please note that in some cases the test2 might return something like:

var test2 = [{"a":1},{},{}] ;  //All these are not empty
var test2 = [{},{"a":1},{}] ;  //All these are not empty
var test2 = [{},{},{"a":1}] ;  //All these are not empty

以上情况不应算作空。我已经试图使用 .length 但它没有帮助,因为长度总是3 ...任何想法?

The above scenarios shouldn't be counted as empty.I've tried to use .length but it's not helping as the length is always 3... Any ideas?

干杯。

推荐答案

function isArrayEmpty(array) {
    return array.filter(function(el) {
        return !jQuery.isEmptyObject(el);
    }).length === 0;
}

jsFiddle演示

通过所有测试。

一个纯JavaScript解决方案是用替换!jQuery.isEmptyObject(el) Object.keys(el).length!= = 0

A pure JavaScript solution would be to replace !jQuery.isEmptyObject(el) with Object.keys(el).length !== 0

编辑:使用 Array.prototype.every

Using Array.prototype.every

function isArrayEmpty(array) {
    return array.every(function(el) {
        return jQuery.isEmptyObject(el);
    });
}

这篇关于检查JSON数组是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆