I am writing a simple nodejs express route that POST's a JSON object.
As a bit of a node/js newbie, I am curious to know if there is an elegant way of testing that a JSON object contains all the attributes that I expect to be submitted and only those attributes?
e.g. if i have a JSON object like this:
data:{
"a":"somevalue".
"b":"somebvalue",
"c":"somecvalue"
}
I was thinking I could do something like:
if( (data.a) && (data.b) && (data.c) ){
//Proceed and process post
else {
// respond with unacceptable
}
Am just wondering if there is a better way, either in JavaScript or express?
Your code is not completely correct for what you're doing. For example for the possible valid object {a:undefined,b:3,c:5} you'd think it does not have the required attributes but in fact it does. A more correct way (assuming the prototype is also fine) would be:
("a" in data) && ("b" in data) && ("c" in data)
If you'd like a solution that scales nicely for multiple properties:
You can use Array.prototype.every:
if(["a","b","c"].every(function(attr){ return attr in data;})){
It's not shorter, but I'd argue it's more semantic, and it doesn't return false positive for empty strings, null and other 'falsy' values. Of course - you can extract this into a function :)