提问者:小点点

对对象内容(值选项)节点应用筛选


我试图通过一个对象,和一些属性,我有有限数量的值,他们可以分配给。下面是我目前检查它们价值的方法:

    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` };
    }

有没有办法对此进行优化?


共1个答案

匿名用户

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

// 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.`);
    }
}

希望这能帮你解决问题。