-1

I use a forEach to access each string in countTargetOptions which is an array of properties that I want to access for the targetData variable.

How can I use element to get each targetData property? My code below shows incorrect syntax as it prints undefined.

const countTargetOptions = [
  "count_targets",
  "count_targets_excluded",
  "count_targets_pending",
  "count_targets_in_progress",
  "count_targets_completed",
  "count_targets_failed",
];

 countTargetOptions.forEach((element: string) =>{
    console.log(targetData.element);
   });

user19251203
  • 322
  • 4
  • 13
  • What is `targetData` and where does it come from? – evolutionxbox Jul 13 '22 at 17:35
  • Does this answer your question? [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Jared Smith Jul 13 '22 at 17:37
  • In addition to *that* problem, unless your `targetData` has an `element` property this shouldn't even *compile*, much less run. You'd need to set `countTargetOptions` to explicitly be `keyof typeof targetData`. – Jared Smith Jul 13 '22 at 17:38
  • @JaredSmith when I do the brackets, I am still getting undefined. Note, without the loop I am able to access the data with `targetData.count_targets` (or any other property). Any further suggestions? – user19251203 Jul 13 '22 at 17:45
  • "Any further suggestions?" Yes. Create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) that we can run. Telling us about your problem in English does not help us help you. That linked dupe fixes a real problem with your code, although maybe not the one you were asking about. – Jared Smith Jul 13 '22 at 17:48

1 Answers1

0

Supposing targetData is an object with all the keys present in countTargetOptions.

const countTargetOptions = [
  "count_targets",
  "count_targets_excluded",
  "count_targets_pending",
  "count_targets_in_progress",
  "count_targets_completed",
  "count_targets_failed",
];

 countTargetOptions.forEach((element: string) =>{
    console.log(targetData[element]);
   });

Also note, countTargetOptions should probably be typed as ArraywhereXXXXis the type oftargetData`.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134