Testing for an empty array object in JSON with jQuery

Tags: json ajax 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:

            function(data) {
                if (data.RoleOwners == [ ]) {
                    $('<tr><td>' + noRoleOwnersText + '</td></tr>').appendTo("#roleOwnersTable tbody");
                $.each(data.RoleOwners, function(i, roleOwner) {
                    var tblRow =
                    + "<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


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

   // anyObjectIncludingJSON i tried for JSON object.


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