1

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.

  • Did you mean `this[index]` instead of `this.index`? – Sebastian Simon Aug 02 '21 at 18:27
  • 2
    there's no need for `this` at all - replace `this.index` with simply `index` and this will work. But `index` is a poor choice of name for the actual array element – Robin Zigmond Aug 02 '21 at 18:28
  • actually, that probably isn't what you want, on reflection - but I have no idea what you *do* want. Could you edit your question to make the input and expected output more clear? – Robin Zigmond Aug 02 '21 at 18:29
  • Will the `fieldName ` value ever actually equal the `fieldValue` value? – Steve Aug 02 '21 at 18:30
  • In your `forEach()` statement, `this` referrs to the `window`. 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 pass the element like this: `forEach((element) => { ... } )`. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Steve Aug 02 '21 at 18:46

1 Answers1

0

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
  })
});
Steve
  • 878
  • 1
  • 5
  • 9