archives

« Bugzilla Issues Index

#3307 — Not able to use RegExp as a key in dictionary


I am not able to do the following:

var regexes = {
new RegExp("@Formula", "i"): "@Formula"
}

however I am able to do:

var regexes = {}
regexes[new RegExp("a", "i")] = "b";


console.log(regexes);

Is this a bug or this is not supposed to work?


(In reply to Suren Nihalani from comment #0)
> I am not able to do the following:
>
> var regexes = {
> new RegExp("@Formula", "i"): "@Formula"
> }
>
you are missing the bracked that must surround a computed property key in an object literal. It should be:

var regexes = {
[new RegExp("@Formula", "i")] : "@Formula"
}


But that would be be a silly thing do do because each time you evaluate
new RegExp("@Formula", "i")
you are going to get a different object with a different === identify. So, nobody culd ever access that property. In a case like the above, what you probably want is something more like:

var formulakey = new RegExp("@Formula", "i")];
var regexes = {
[formulakey] : "@Formula"
};
...
regexes[formulakey] = ...


>
> Is this a bug or this is not supposed to work?

neither, you seem to misunderstand the syntax and semantics of computed property names.


Got it. Thanks a lot.

I decided to use a dict because I wanted to iterate over key, value pairs in a dict and wanted the collect the values only when the key's regex was passing on the string I was working with. I didn't plan to look up the property later, I was going iterate through the map. Hope that helps in understanding the use case.