NodeJS: Detect if an Object is empty or not


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.