【问题标题】:Apply filtering to object content (value options) nodejs [closed]将过滤应用于对象内容(值选项)nodejs [关闭]
【发布时间】:2021-07-12 05:01:26
【问题描述】:

我正在尝试查看一个对象和一些属性,我可以将它们分配给的值数量有限。以下是我目前检查它们的价值的方法:

    for (const [attribute, value] of Object.entries(params.object)) {
      if(attribute == "accountType")
        if(value != "external" && value != "internal") 
          return { status: `Failed! '${attribute}' must only equal to 'internal' or 'external'` };
      else if(attribute == "dnsName")
        if(value.match('^[a-z]*-[0-9]*$') == null) 
          return { status: `Failed! '${attribute}' must follow the pattern [a-z]*-[0-9]*` };
      else if(attribute == "edition")
        if(value != "starter" && value != "basic" && value != "classic") 
          return { status: `Failed! '${attribute}' must only equal to 'starter', 'basic' or 'classic'` };
      else if(attribute == "forceProvision" || attribute == "installSoltions")
        if (typeof value !== "boolean")
            return { status: `Failed! '${attribute}' must be of type boolean true/false` };
    }

有没有办法优化这个?

【问题讨论】:

  • 为了每个人的理智,即使是单语句 if 正文也要使用大括号,尤其是在使用多个 ifelse if 时! Javascript 不关心您的缩进级别...

标签: javascript node.js object filter lodash


【解决方案1】:

对于不需要模式匹配的简单情况,您可以指定格式对象并执行以下操作:

// the arrays represent the possible values an object respecting this format can take.
let format = {
    greeting: ['hello', 'goodbye'],
    direction: ['right', 'left'] 
}

// here's a test object that does not respect said format.
let a = {
    greeting: 'hello',
    direction: 'not a desirable value'
};

for(const [attribute, value] of Object.entries(a)) {
    // - 1 on indexOf means not present in array. Here we check that the
    // value of the attribute respects the format.
    if(format[attribute].indexOf(value) == -1) {
        console.log(`Incorrect format for ${attribute}, expected ${format[attribute]}`);
    } else {
        // saul'goodman
        console.log(`${attribute} correctly formatted.`);
    }
}

希望这可以帮助您解决问题。

【讨论】:

  • 类型检查或模式匹配怎么样?
  • 更新了描述以反映@charlietfl 对模式匹配的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2018-09-07
相关资源
最近更新 更多