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

5 Answers 5

26
(data.RoleOwners.length === 0)
Sign up to request clarification or add additional context in comments.

4 Comments

I don't understand. Why -1? „![].length“ — would be shorter and correctly, imho.
Agreed, should be .length === 0, or ![].length as said above. Either way this question is not about JSON objects at all, but Javascript arrays.
Lol thanks for that, thought I'd tried that, but I must have tried .Length instead.
23

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

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

1 Comment

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
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;
            }

1 Comment

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
1

Check this

JSON.parse(data).length > 0

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.