如何判断 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

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

How to tell if JSON object is empty in jQuery

javascriptjquery

提问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

Use Array's lengthproperty:

使用 Array 的length属性:

// note: you don't even need '== 0'

if (data.objects.length == 0) {
  alert("Empty");
}
else {
  alert("Not empty");
}

回答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:

出于某种原因,它是最好的 - 它不仅检查对象是否为空,而且还检查:

  1. objectsexists on data
  2. objectsis an array
  3. objectsis a non-empty array
  1. objects存在于 data
  2. objects是一个数组
  3. objects是一个非空数组

All of these checks are important. If you don't check that objectsexists and is an array, your code will break if the API ever changes.

所有这些检查都很重要。如果您不检查它是否objects存在并且是一个数组,那么如果 API 发生更改,您的代码就会中断。

回答by Rory McCrossan

You can use the lengthproperty 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