在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
使用JSON.stringify怎么样?它几乎可以在所有现代浏览器中使用。
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
其他回答
任何类型的值都为空
/* eslint-disable no-nested-ternary */
const isEmpty = value => {
switch (typeof value) {
case 'undefined':
return true;
case 'object':
return value === null
? true
: Array.isArray(value)
? !value.length
: Object.entries(value).length === 0 && value.constructor === Object;
case 'string':
return !value.length;
default:
return false;
}
};
这与在lodash源中检查对象的方式类似:
const isEmpty = value => {
for (const key in value) {
if (hasOwnProperty.call(value, key)) {
return false
}
}
return true;
}
但有很多其他方法可以做到这一点。
要真正接受ONLY{},在Javascript中使用Lodash的最佳方法是:
_.isEmpty(value) && _.isPlainObject(value)
let jsObject = JSON.parse(JSON.stringify(obj), (key, value) => {
if (value === null ||
value === '' ||
(value.constructor === Object && Object.entries(value).length === 0) ||
(value.constructor === Array && value.length === 0)) {
return undefined
}
return value
})
这将递归地过滤掉所有无效字段。
如果ECMAScript 5支持可用,则可以使用Object.keys():
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
对于ES3和更高版本,没有简单的方法可以做到这一点。您必须显式循环财产:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}