简体   繁体   English

JSON 数组是否为空

[英]JSON array empty or not

我有一个数组var st = { "itema":{...},"itemb":[{"id":"s01","cd":"c01","dd":"d01",....}{"id":"s02","cd":"c02","dd":"d02",....}]}如何检查 st 是否为空?

You can use Object.getOwnPropertyNames() to see whether there are any object properties:您可以使用Object.getOwnPropertyNames()来查看是否有任何对象属性:

if (Object.getOwnPropertyNames(st).length === 0) {
  // no properties
}

Now, if there are properties, it's up to you to decide whether an object with properties whose values are undefined or null is "empty" or not.现在,如果特性,它是由你来决定用其值属性的对象是否undefinednull是“空”或没有。

Another approach that might more closely reflect your concept of "empty" would be to stringify the object as JSON:另一种可能更接近地反映您的“空”概念的方法是将对象字符串化为 JSON:

var __EMPTY = JSON.stringify({});
// ...
if (JSON.stringify(st) === __EMPTY) {
  // ...
}

Not the most efficient thing to do of course if your object might be relatively large in common cases.如果您的对象在常见情况下可能相对较大,这当然不是最有效的做法。

The concept of an "empty object" really isn't very natural in JavaScript, at least in my experience. “空对象”的概念在 JavaScript 中确实不是很自然,至少在我的经验中是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM