0

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.

1
  • You can't have key:value pairs in an array, only in an object. Commented Apr 27, 2020 at 18:13

1 Answer 1

1

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);
  }
});

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This does seem to work, but it no longer is matching how it was previously in cases where there is only one group
Right, this only works for the new problem. You can use the old code for the original replacements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.