使用 jQuery 测试 JSON 中的空数组对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/334836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:59:00  来源:igfitidea点击:

Testing for an empty array object in JSON with jQuery

jqueryajaxjson

提问by mattcole

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?

我有一个请求,它返回一个带有单个属性的 JSON 对象,该属性是一个数组。如何测试数组是否为空?

With jQuery code like:

使用 jQuery 代码,例如:

 $.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?

我可以用什么代替 if(data.RoleOwners == [ ]) 来测试 RoleOwners 是否为空数组?

Thanks, Matt

谢谢,马特

回答by svinto

(data.RoleOwners.length === 0)

回答by Sadiksha Gautam

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

你也可以这样做 jQuery.isEmptyObject(data.RoleOwners)

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

查看http://api.jquery.com/jQuery.isEmptyObject/

回答by Arun Pratap Singh

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

下面的代码工作得很好,不需要自己写一个。

   // anyObjectIncludingJSON i tried for JSON object.

         if(jQuery.isEmptyObject(anyObjectIncludingJSON))
            {
                return;
            }

回答by Sameera Prasad Jayasinghe

Check this

检查这个

JSON.parse(data).length > 0

回答by John Middlemas

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
}