0

If you look at the JSON posted further below, I have several objects named row0, row1, row2 etc...

The code I posted further below works but not as intended. The problem lies with the following line:

for (let key in movies.row1) {

I hard coded row1 but I really want to achieve is row1 then row2 then row3 etc...

So I want to insert the value of i into the name of the object after the word row...

movies.rowi <--- i needs to be a variable not the letter i.

I tried a few guesses from googling and stackoverflow like movies.row${[i]} but nothing worked. Also, tried spread operator something like movies.row[1...6] but its invalid.

  function display_all_movies(movies) {

    for (i = 0; i < movies.row_count.count; i++) {

    for (let key in movies.row1) {

       document.getElementById("moviesList").innerHTML += `Key: ${key}` + `Value: ${movies.row1[key]}` + '<br>';

    }
  }
}

movies is an object in JSON format, which is validated. Movies JSON is as follows:

{"row0" : {"title":"Avengers","imgName":"Avengers.jpeg","addedBy":"MrCoolDude","stars":"4"},"row1" : {"title":"Spiderman","imgName":"Spiderman.jpeg","addedBy":"TheNumber2Dude","stars":"5"},"row2" : {"title":"Conair","imgName":"conair.png","addedBy":"Eagleuser","stars":"3"}, "row_count" : {"count" : "4"},"row3" : {"title":"Robin","imgName":"Robin.jpeg","addedBy":"UserBatman","stars":"4"}}
Steve
  • 23
  • 3

1 Answers1

0

Use bracket notation for dynamic property access.

for (let i = 0; i < movies.row_count.count; i++) {
    for (let key in movies[`row${i}`]) {
        document.getElementById("moviesList").innerHTML += `Key: ${key}` + `Value: ${movies[`row${i}`][key]}` + '<br>';
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Your the best, that works! If possible, could you also fix the Value: ${movies.row1[key]} part?... I keep getting undefined. I'll keep trying to format the above solution for that line as well. – Steve Jun 18 '22 at 00:19