Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
Insert a variable into an objects name in Javascript

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"}}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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>';
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!