在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
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
})
这将递归地过滤掉所有无效字段。
其他回答
您可以使用Undercore.js。
_.isEmpty({}); // true
您可以使用lodash库而不是创建一个简单的JS函数。
_.isEmpty({})//真
这将检查数组和对象是否有值并返回布尔值。
function isEmpty(obj) {
for(var i in obj) { return false; }
return true;
}
jQuery在这种情况下具有特殊的函数isEmptyObject():
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
阅读更多信息http://api.jquery.com/jQuery.isEmptyObject/
任何类型的值都为空
/* 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;
}
};