How do I test for an empty JavaScript object?
Advertisement
How do I test for an empty JavaScript object?
Question
After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
2020/01/17
Accepted Answer
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object
Note, though, that this creates an unnecessary array (the return value of keys
).
Pre-ECMA 5:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
jQuery.isEmptyObject({}); // true
_.isEmpty({}); // true
_.isEmpty({}); // true
Hoek.deepEqual({}, {}); // true
Ext.Object.isEmpty({}); // true
angular.equals({}, {}); // true
R.isEmpty({}); // true
2020/03/08
Read more… Read less…
There's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
If ECMAScript 5 support is available, you can use Object.keys()
instead:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
2014/08/29
For those of you who have the same problem but use jQuery, you can use jQuery.isEmptyObject.
2020/05/18
This is my preferred solution:
var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
2014/07/12
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
see http://bencollier.net/2011/04/javascript-is-an-object-empty/
2013/11/06
Licensed under CC-BY-SA with attribution
Not affiliated with Stack Overflow
Email: [email protected]