Return to Snippet

Revision: 65497
at December 8, 2013 12:11 by chrisaiv


Initial Code
exports.test = function(req, res){
    var params = req.query;
    if( !isEmpty(params) ) res.json( params );
    else res.json( { message: "no request query" } )
};

//http://stackoverflow.com/questions/4994201/is-object-empty
function isEmpty(obj) {
    // null and undefined are "empty"
    if (obj == null) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length && obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and toValue enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

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

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

Initial Title
NodeJS: Detect if an Object is empty or not

Initial Tags

                                

Initial Language
JavaScript