【问题标题】:How to validate the key and value not to be empty in array?如何验证键和值在数组中不为空?
【发布时间】:2022-02-16 01:11:02
【问题描述】:

参数验证 我想确保数组不能为空,以便验证数组

imgList= [ { “文件类型”:“png”, “文件内容”:“base64” }, { “文件类型”:“png”, “文件内容”:“base64” } ] 我想验证键和值是否存在(不应该为空)

eg: filetype is missing
   {
    
      "fileContent": "base64"
    },
eg2: value is missing
    {
      "fileType": "",
      "fileContent": "base64"
    },

我厌倦的代码是

body.imgList.forEach((item) => {
      var key,
        count = 0;
      for (let [key, value] of Object.entries(item)) {
        if (item.hasOwnProperty(key) && !!value) {
          count++;
        }
      }
      var objectLenght = count;
      if (objectLenght != 2) {
        return cb({"status_code":400,"status":"Pass all the required fields"});
      }   
    });

当我尝试这个工作时,它已经死了,并且上传的图片没有在 s3 中输入

【问题讨论】:

    标签: node.js angular


    【解决方案1】:

    我希望这可行,您可以使用 isOkay 函数来验证数组是否有效

    const isOkay = (arr)=> {
    let okay = true;
    for(let entry of arr){
      if(!entry.hasOwnProperty('fileType') || !entry['fileType'] || !entry.hasOwnProperty('fileContent') || !entry['fileContent']){
        okay = false; 
        break;
      }
    }
    return okay;
    }
    

    【讨论】:

      【解决方案2】:

      Javascript 的 truthy / falsy 系统会为您解决这个问题。如果密钥不存在,您将在尝试访问它时得到undefined,即falsy。空字符串也是falsy 值。

      function validate(data) {
        if (!data || !data.length) return false;
        for (const item of data) {
          if (!item || !item.fileType || !item.fileContent) return false;
        }
        return true;
      }
      
      if (validate(body.imgList)) return cb({ status_code: 400, status: 'Pass all the required fields' });;
      

      更多信息falsy: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        • 2018-11-14
        相关资源
        最近更新 更多