Lurk21
Lurk21

Reputation: 2337

Javascript: How to test if response JSON array is empty

I'm getting back the following JSON:

{"array":[],"object":null,"bool":false}

And I'm testing it with the following, seemingly exhaustive, if statement:

$.ajax({
        type: "GET",
        url: "/ajax/rest/siteService/list",
        dataType: "json",
        success: function (response) {
            var siteArray = response.array;

            // Handle the case where the user may not belong to any groups
            if (siteArray === null || siteArray=== undefined || siteArray=== '' || siteArray.length === 0) {
                            window.alert('hi');
            }
       }
});

But the alert is not firing. :[

Upvotes: 15

Views: 53197

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Use $.isArray() to check whether an object is an array. Then you can check the truthness of the length property to see whether it is empty.

if( !$.isArray(siteArray) ||  !siteArray.length ) {
    //handler either not an array or empty array
}

Upvotes: 28

Phrogz
Phrogz

Reputation: 303224

Two empty arrays are not the same as one another, for they are not the same object.

var a = [];
if (a === []){
  // This will never execute
}

Use if (siteArray.length==0) to see if an array is empty, or more simply if (!siteArray.length)

Upvotes: 7

Related Questions