Posted By

chrisaiv on 12/08/13


Tagged

nodejs


Versions (?)

NodeJS: Detect if an Object is empty or not


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/4994201/is-object-empty

Using ExpressJS, I wanted a simple function that would respond (through JSON) whether a request query was present or not.

  1. exports.test = function(req, res){
  2. var params = req.query;
  3. if( !isEmpty(params) ) res.json( params );
  4. else res.json( { message: "no request query" } )
  5. };
  6.  
  7. //http://stackoverflow.com/questions/4994201/is-object-empty
  8. function isEmpty(obj) {
  9. // null and undefined are "empty"
  10. if (obj == null) return true;
  11.  
  12. // Assume if it has a length property with a non-zero value
  13. // that that property is correct.
  14. if (obj.length && obj.length > 0) return false;
  15. if (obj.length === 0) return true;
  16.  
  17. // Otherwise, does it have any properties of its own?
  18. // Note that this doesn't handle
  19. // toString and toValue enumeration bugs in IE < 9
  20. for (var key in obj) {
  21. if (hasOwnProperty.call(obj, key)) return false;
  22. }
  23.  
  24. return true;
  25. }

Report this snippet  

You need to login to post a comment.