Austin
Austin

Reputation: 335

Regex match group based on array with key value

Here is what I'm currently doing to match values in the vars array with object keys inside of newaction.

Object.keys(newaction).forEach((e) => {
        try {
            var newVal = newaction[e].replace(regex, (_match, group1) => vars[group1]);
            newaction[e] = newVal;
        } catch (err) {
            console.log(err);
        }
    });

So each matching property of newaction will be replaced by the value in vars which has a matching key.

What I'm trying to do now is replace the value in newaction with the matching value in vars, but where the value in vars is an array.

So say vars looks like this:

[{
    "name": "test",
    "value": ["HP": '35',
    "Atk": '55',
    "Def": '30',
    "SpA": '50',
    "SpD": '40',
    "Spe": '90',]
}]

If I now want to match it in the form of newvalue[e] being test[HP] to get the value '35', the original regex does not work.

Upvotes: 0

Views: 232

Answers (1)

Barmar
Barmar

Reputation: 780787

Change vars to an object whose key is the name and value is the object with the key:value pairs. Then you can use the two groups as indexes into the main object and nested object.

vars = {
  "test": {
    "HP": '35',
    "Atk": '55',
    "Def": '30',
    "SpA": '50',
    "SpD": '40',
    "Spe": '90'
  }
};

const regex = /(\w+)\[(\w+)\]/;
Object.keys(newaction).forEach((e) => {
  try {
    var newVal = newaction[e].replace(regex, (_match, group1, group2) => vars[group1][group2]);
    newaction[e] = newVal;
  } catch (err) {
    console.log(err);
  }
});

Upvotes: 1

Related Questions