During some tests I found at least 3 ways to check if object “is empty”. I mean, do not contains any enumerable properties. Assuming we have an object:
<code lang="javascript">var obj = {};</code>
Then we can use:
if(JSON.stringify(obj) == '{}'){ // object is "empty" }
or
if(Object.keys(obj).length == 0){ // object is "empty" }
or
var isObjectEmpty = function (obj) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { return false; } } return true; }; if(isObjectEmpty(obj)){ // object is "empty" }
Note: window.JSON
method is not available in IE7 and lower natively. Also, Object.keys
doesn’t work in IE < 9.
Leave a Reply