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.
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);
});
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With