Reputation: 2758
var http = require('http'),
url = require('url'),
route = require('router')();
...
route.get('/{betNameType}', function(req, res) {
var query = url.parse(req.url, true).query;
if (!Object.keys(query).length) {
// query string is empty
}
else {
// query string is set
}
}
Hello everyone!.
I'm fairly new to javacript / node.js. I wonder if it is possible to simplify my code. Specifically the part that validates if "query" is empty. With my knowledge I did not find an easier way
Upvotes: 2
Views: 3213
Reputation: 276496
Your method works.
In the general case of checking an object it fails on the edge case of un-enumerable properties which should not be an issue with the query string (link to source code) and can be resolved by using Object.getOwnPropertyNames
instead of Object.Keys
.
Given you are running nodejs and not browser JavaScript, using Object.Keys
is probably the cleanest you're going to get for checking if an object has no enumerable properties. The only thing I'd change is explicitly writing .length===0
instead of .length
since this is what you are in fact checking (that the object has no keys, and not that its key could is falsy)
You might find this question useful.
Upvotes: 1