I\'m looking for an good / elegant way to validate that a javascript object has the required properties, so far this is what I have:
var fields = [\'name\',\
I think that you should be more concerned about what's the proper way of checking for it, rather than the most elegant. I'll drop a link to a very good post from Todd Moto regarding this: Please, take a look
In short your code should look like this:
var validateFields = function(o, required_fields) {
required_fields.forEach(function(field){
if(field in o){
if((typeof o[field] != 'undefined')){
console.log(field + ": " + o[field]);
}else{
console.log(field + " exists but is undefined");
}
}else{
console.log(field + " doesn't exist in object");
}
});
}
Note: Take care when checking it has value, many expressions in javasscript are falsy (eg. 0, false, etc.) but are valid values.