cocacrave cocacrave - 2 months ago 21
Javascript Question

Javascript RegEx Nested Object Key

I have a preset object which has bunch of keys like this:

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


I tried using regex like this:

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


Now I want to use it to test the keys of preset.
I tried to many different ways but eslint keeps giving me syntax error:

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

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


etc.

This is for db schema, if I don't use regEx, it's going to be super long to check. Can someone help?

Answer

You can't check property's names by trying to access them by regexp object. You need to iterate over object property's and check their name.

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