如何判断 JSON 对象在 jQuery 中是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19730244/
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
How to tell if JSON object is empty in jQuery
提问by GrantU
I have the following JSON:
我有以下 JSON:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 0
},
"objects": []
}
I'm interested in objects: I want to know if objects is empty and show an alert:
我对对象感兴趣:我想知道对象是否为空并显示警报:
something like this:
像这样:
success: function (data) {
$.each(data.objects, function () {
if data.objects == None alert(0)
else :alert(1)
});
回答by GilbertSun
i don't know what is you meaning about empty object, but if you consider
我不知道你对空对象的意思是什么,但如果你考虑
{}
as a empty object, i suppose you use the code below
作为一个空对象,我想你使用下面的代码
var obj = {};
if (Object.keys(obj).length === 0) {
alert('empty obj')
}
回答by ComFreek
回答by tybro0103
This is the best way:
这是最好的方法:
if(data.objects && data.objects.length) {
// not empty
}
And it's the best for a reason - it not only checks that objects is not empty, but it also checks:
出于某种原因,它是最好的 - 它不仅检查对象是否为空,而且还检查:
objects
exists ondata
objects
is an arrayobjects
is a non-empty array
objects
存在于data
objects
是一个数组objects
是一个非空数组
All of these checks are important. If you don't check that objects
exists and is an array, your code will break if the API ever changes.
所有这些检查都很重要。如果您不检查它是否objects
存在并且是一个数组,那么如果 API 发生更改,您的代码就会中断。
回答by Rory McCrossan
You can use the length
property to test if an array has values:
您可以使用该length
属性来测试数组是否具有值:
if (data.objects.length) {
$.each(data.objects, function() {
alert(1)
});
}
else {
alert(0);
}
回答by Justis Matotoka
this was what i did, thanks @GilbertSun, on a jsonp callback when I got an undefined with data.objects.length
这就是我所做的,感谢@GilbertSun,当我得到一个未定义的 data.objects.length 时,在 jsonp 回调中
success: function(data, status){
if (Object.keys(data).length === 0) {
alert('No Monkeys found');
}else{
alert('Monkeys everywhere');
}
}
回答by Guilherme Soares
Js
JS
var myJson = {
a:[],
b:[]
}
if(myJson.length == 0){
//empty
} else {
//No empty
}
Only jQuery:
只有jQuery:
$(myJson).isEmptyObject(); //Return false
$({}).isEmptyObject() //Return true