javascriptwdio-v5

Extracting selector variable names from JSON data


Given the following json:

{
  "contract": [
    {"fieldName": "contractYear", "fieldValue": "2020"},
    ...
  ],
  "ruleSet": [
    ...
  ]
}

And the following:

staticCompany.contract.forEach(index => {
  if (this.index.fieldName.getText() == index.fieldValue) {
    validationCount ++;
  }
});

I know for a fact that the this. operator will not like what I am trying to do. Is there a way to extract the fieldName such that I can use it to hit the selector of the same name?

I am doing this in Node 12.13 on wdio v5.


Solution

  • In your forEach() statement, this referrs to the window, so you won't want to use that.

    Also, the for each is only passing in the index number of the array. If you want to see the values in the forEach() you need to include the element as well (Okay, technically in your for each, index is bringing back the element because it is listed first, but syntactically it gets confusing if you are using index when it isn't actually the index).

    All of these are valid options:

    forEach((element) => { ... } )
    forEach((element, index) => { ... } )
    forEach((element, index, array) => { ... } )
    

    See MDN: Array.ForEach() for more info.

    In the snippet below, I added in a second Object element into the contract array to show you how you can access each Object element in that array, and get the values from it.

    const staticCompany = {
      "contract": [{
          "fieldName": "contractYear",
          "fieldValue": "2020"
        },
        {
          "fieldName": "contractYear",
          "fieldValue": "2021"
        },
      ],
      "ruleSet": []
    }
    
    staticCompany.contract.forEach((element, index) => {
      console.log({
        index: index,
        fieldName: element.fieldName,
        fieldValue: element.fieldValue
      })
    });