Testing for an empty array object in JSON with jQuery

Tags: json ajax jquery
Question!

I have a request that returns a JSON object with a single property which is an array. How can I test if the array is empty?

With jQuery code like:

 $.getJSON(
            jsonUrl,
            function(data) {
                if (data.RoleOwners == [ ]) {
                    $('<tr><td>' + noRoleOwnersText + '</td></tr>').appendTo("#roleOwnersTable tbody");
                    return;
                }
                $.each(data.RoleOwners, function(i, roleOwner) {
                    var tblRow =
                    "<tr>"
                    + "<td>" + roleOwner.FirstName + "</td>"
                    + "<td>" + roleOwner.LastName + "</td>"
                    + "</tr>"
                    $(tblRow).appendTo("#roleOwnersTable tbody");
                });

what can I put instead of if(data.RoleOwners == [ ]) to test if the RoleOwners is an empty array?

Thanks, Matt

By : mattcole


Answers

below code works perfectly fine no need to write one of yours own.

   // anyObjectIncludingJSON i tried for JSON object.

         if(jQuery.isEmptyObject(anyObjectIncludingJSON))
            {
                return;
            }


An array (being an object too) can have non numeric properties which are not picked up by testing for zero length. You need to iterate through the properties just like testing for an empty object. If there are no properites then the array is empty.

function isEmptyObject(obj) {
   // This works for arrays too.
   for(var name in obj) {
       return false
   }
   return true
}


You can also do jQuery.isEmptyObject(data.RoleOwners)

check out http://api.jquery.com/jQuery.isEmptyObject/



This video can help you solving your question :)
By: admin