22

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

mattcole
  • 1,229
  • 2
  • 12
  • 22

5 Answers5

26
(data.RoleOwners.length === 0)
Svante Svenson
  • 12,315
  • 4
  • 41
  • 45
23

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

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

Sadiksha Gautam
  • 5,032
  • 6
  • 40
  • 71
  • 2
    This answer worked when an empty array or a null array is passed through the data result (The accepted answer didn't) thanks for this – JakeJ Apr 24 '12 at 13:42
4

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

   // anyObjectIncludingJSON i tried for JSON object.

         if(jQuery.isEmptyObject(anyObjectIncludingJSON))
            {
                return;
            }
Arun Pratap Singh
  • 3,428
  • 30
  • 23
  • Arun, I observed that you have good understanding on jQuery apis, you have always given reference of Jquery's inbuilt apis rather than re-inventing ..wheels..good – Archana Mundaye Nov 27 '15 at 07:31
1

Check this

JSON.parse(data).length > 0
0

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
}