Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a JSON array is empty

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

I am receiving back a JSON array as:

var test1 = [] ;

or

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

I have no problem finding out if test1 is empty.

jQuery.isEmptyObject(test1)

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

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?

Cheers.

like image 425
Thanos Avatar asked Aug 23 '13 06:08

Thanos


2 Answers

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

jsFiddle Demo

Passes all of your tests.

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

Edit: Using Array.prototype.every

function isArrayEmpty(array) {
    return array.every(function(el) {
        return jQuery.isEmptyObject(el);
    });
}
like image 68
c.P.u1 Avatar answered Sep 17 '22 16:09

c.P.u1


For those playing at home, a non jQuery solution:

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

function isEmpty(val) {
    var len = val.length,
        i;

    if (len > 0) {
        for (i = 0; i < len; ++i) {
            if (!emptyObject(val[i])) {
                return false;
            }
        }
    }
    return true;
}

function emptyObject(o) {
    for (var key in o) {
        if (o.hasOwnProperty(key)) {
            return false;
        }
    }
    return true;
}

console.log(isEmpty(test2));
like image 29
Evan Trimboli Avatar answered Sep 16 '22 16:09

Evan Trimboli