Javascript - elegant way to check object has required properties

后端 未结 3 550
醉话见心
醉话见心 2021-01-03 01:26

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\',\         


        
3条回答
  •  臣服心动
    2021-01-03 01:49

    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.

提交回复
热议问题