Javascript RegEx嵌套对象键

时间:2016-07-13 01:38:16

标签: 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}

这是针对db架构的,如果我不使用regEx,那么检查它会超长。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您无法通过regexp对象访问属性来检查属性的名称。您需要遍历对象属性并检查其名称。

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