Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for an empty array object in JSON with jQuery

Tags:

json

jquery

ajax

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

like image 935
mattcole Avatar asked Dec 02 '08 17:12

mattcole


People also ask

How do I check if an array is empty in JSON?

You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not.

Can you have an empty array in JSON?

JSON data has the concept of null and empty arrays and objects.

How do you check if an element in an array is empty Javascript?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.


4 Answers

(data.RoleOwners.length === 0)
like image 197
Svante Svenson Avatar answered Oct 10 '22 11:10

Svante Svenson


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

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

like image 43
Sadiksha Gautam Avatar answered Oct 10 '22 10:10

Sadiksha Gautam


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

   // anyObjectIncludingJSON i tried for JSON object.

         if(jQuery.isEmptyObject(anyObjectIncludingJSON))
            {
                return;
            }
like image 24
Arun Pratap Singh Avatar answered Oct 10 '22 09:10

Arun Pratap Singh


Check this

JSON.parse(data).length > 0
like image 1
Sameera Prasad Jayasinghe Avatar answered Oct 10 '22 09:10

Sameera Prasad Jayasinghe