Home > OS >  Retrieving value from an object using regex - JS
Retrieving value from an object using regex - JS

Time:12-20

Is it possible to extract a value from an object by regex on its key?

example:

var map= {"xxx_yyy":{///some props}};

var receiverId = "xxx";

var regex = new RegExp(`${receiverId}_[^\\n]`);

I would like something like this:

map[regex]

Highlights:

  • When building the map object I do not give an option to a dupliacte xxx_ (example: if i have xxx_yyy, xxx_zzz will not happen - so the regex xxx_[ANYTHING] is unique)
  • I do not want to use a loop, because then I lose the effect of the object built as a kind of hash table.

CodePudding user response:

for (const [key, value] of Object.entries(map)) {
  if(regex.test(key))
  {
      // key matches the regex: do whatever you would like
  }
}

CodePudding user response:

Works - we turned the whole object into STRING and searched for the KEY in it by regex - then we extracted the value according to the full KEY (no loops :))

var map= {"xxx_yyy":{status:"a"}};
var receiverId = "xxx";
var regex = new RegExp(`"${receiverId}_[^\\n] ?"`,"g");
var mapString = JSON.stringify(map);
var match = mapString.match(regex);
if(match[0])

{
    var key = match[0].replace(/"/g,"");
    var val = map[key];
}
  • Related