0

How can I loop through this array with a partial string?

So the word "Brian" needs to be added onto the end of "profile".

var myString = "Brian";

for (k = 0; k < gameData.courseProfiles[i].profile"+myString+".length; k++) {

    var andrew = gameData.courseProfiles[i].profile"+myString+"[k].type;

console.log (andrew);

                }
Phil
  • 157,677
  • 23
  • 242
  • 245
Andrew Howard
  • 2,818
  • 5
  • 33
  • 59
  • `gameData.courseProfiles[i]['profile'+myString]` – blex Mar 26 '15 at 22:36
  • 1
    @blex The last dot is obsolete. – Etheryte Mar 26 '15 at 22:36
  • This is not JSON. This is a nested JavaScript object/array. JSON is **language-independent**, **textual** data representation, much like XML, YAML or CSV. – Felix Kling Mar 26 '15 at 22:37
  • I tried this but it didn't work: for (k = 0; k < gameData.courseProfiles[i].['profile' + randomProfileNumber].length; k++) { var andrew = gameData.courseProfiles[i].['profile' + randomProfileNumber][k].type; console.log (andrew); } – Andrew Howard Mar 26 '15 at 22:40
  • @Andrew: `].[` -> `][`. I highly recommend to read the [MDN JavaScript guide about objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects). – Felix Kling Mar 26 '15 at 22:41

1 Answers1

1

You need to use the bracket notation.

gameData.courseProfiles[i]["profile" + myString];
Etheryte
  • 24,589
  • 11
  • 71
  • 116