Thursday, April 27, 2017

How do I test for an empty JavaScript object?



After an AJAX request, sometimes my application may return an empty object, like:



var a = {};



How can I check whether that's the case?


Answer



ECMA 7+:



// because Object.entries(new Date()).length === 0;
// we have to do some additional check
Object.entries(obj).length === 0 && obj.constructor === Object


ECMA 5+:




// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object


Pre-ECMA 5:



function isEmpty(obj) {
for(var prop in obj) {

if(obj.hasOwnProperty(prop)) {
return false;
}
}

return JSON.stringify(obj) === JSON.stringify({});
}


jQuery:




jQuery.isEmptyObject({}); // true


lodash:



_.isEmpty({}); // true


Underscore:




_.isEmpty({}); // true


Hoek



Hoek.deepEqual({}, {}); // true


ExtJS




Ext.Object.isEmpty({}); // true


AngularJS (version 1)



angular.equals({}, {}); // true


Ramda




R.isEmpty({}); // true

No comments:

Post a Comment