views:

104

answers:

4

I have a two level JSON object

EX:

  var regexDefs = { 

      "alpha": {
          "regex"  : /^[A-Z]+$/,
          "errMsg" : "Alpha Only" }
      }

I want to do something akin to searching an array for a key.

(using jQuery's inArray)

var key = "alpha";
alert($.inArray(key,regexDefs));

if the key is in the array then I want to do

if(regexDefs[key].regex.test){ return true; }

I know there may be something funky I'm missing because this is an object not an Array...

doing

$.inArray(key,regexDefs)

returns undefined

=/

Any thoughts?

+2  A: 

Just do:

if (regexDefs[key]) {
    // Present.
} else {
    // Not present.
}

To learn more about JSON, I can recommend you Mastering JSON.

BalusC
ok this worked. I guess i dont need to search
codeninja
Check however the answer of Andy E for a tad more robust way :)
BalusC
@BalusC: A reciprocal +1 seems in order, your method will work just as elegantly if you're certain `key` won't be a falsey value :-)
Andy E
+1  A: 
if (regexDefs['alpha']) {
    // alpha exists in regexDefs
});
David
+1  A: 

If the key is stored in a variable named key, you can use something like:

if(regexDefs[key]) {
    // do your thing
}
patrick dw
+4  A: 

The most accurate way is

if ("alpha" in regexDefs)
{
}

This would evaluate true even if alpha was a falsey value such as 0, null, NaN, false, etc.

You can do the same with a variable:

var key = "alpha";
if (key in regexDefs)
{
}
Andy E
+1 this is indeed more robust.
BalusC