Javascript RegEx 嵌套对象键



我有一个预设对象,它有一堆这样的键:

preset: {
  abc: { type: Boolean, optional: true},
  bcd: { type: Boolean, optional: true},
  def: { type: Boolean, optional: true},
  efg: { type: Boolean, optional: true},
}

我尝试像这样使用正则表达式:

regEx: {
  test: /abc|bcd|def|efg/,
}

现在我想用它来测试预设的键。我尝试了许多不同的方法,但 eslint 不断给我语法错误:

preset.[regEx.test]: { type: Boolean, optional: true}
[`preset.${regEx.test}`]: { type: Boolean, optional: true}

等。

这是针对数据库模式的,如果我不使用正则表达式,检查时间会很长。有人可以帮忙吗?

您无法通过尝试通过正则表达式对象访问属性的名称来检查属性的名称。您需要遍历对象属性并检查其名称。

for( var i in preset ) if( preset.hasOwnProperty( i ) ) {
    if( regEx.test.test( i ) ){
       var item = preset[i]
       //this is valid property name
       if( item.type === Boolean && item.optional === true ){ 
           // some other checks
       } else {
           //not boolean or not optional
       }
    } else {
       //this is not valid property name
    }
}

最新更新