Testing for an empty array object in JSON with jQuery

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

Answers


(data.RoleOwners.length === 0)

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

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


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
}

Check this

JSON.parse(data).length > 0

Need Your Help

How to open a PDF file without any package?

r pdf

Im trying to open a pdf file which is my working directory. here is code

Find any special characters in a string

lua lua-patterns

I still struggle big time to match a string that contains the special characters (punctuation, underlines, etc). How can I make it work with patterns?