Can I set a regular expression for an object / property selector method?

var regxp = /[\S]/; //any char, not sure if it /.*/ or something else var obj = { atr1: "bla" } var blahs = obj[regxp]; //returns atr1 

I am looking for a shortcut to get method / property names from an object, because for..in slower compared to a for loop, for example. I want this for a special case when I know that an object will have only one method / property

0
source share
3 answers

Yes, you can try to access the property of an object using a regular expression, but no, it won’t do what you want: it converts the regular expression to a string and uses that property name.

The only way to find the name of a property in an object by matching with a regular expression is for ... in loop, as you mentioned. Performance should not be a problem if an object has only one property.

 function findPropertyNameByRegex(o, r) { for (var key in o) { if (key.match(r)) { return key; } } return undefined; }; findPropertyNameByRegex(obj, regxp); // => 'atr1' 
+2
source

your regular expression will match one non-spatial character.

for...in is a loop. is it slower than what? did you compare?

if you want to search for properties using regex, you have to do it in a loop.

 for(var k in obj) { if(regexp.match(k)) { // do whatever } } 
0
source

If you have only one property, you can be sure that for..in will not be slow.

0
source

Source: https://habr.com/ru/post/1242347/


All Articles