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
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.
JSON data has the concept of null and empty arrays and objects.
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.
(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;
}
Check this
JSON.parse(data).length > 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With