loop through Json structure in Javascript

Question: Just wondering , what is the best way to loop items in the inner structure of a Json file. Like "showtimes" key here ?

My Json file:

var movies_list = {
    "movies":[  
   {  
      "id":"1",
      "name":"Finding Nemo",
      "audience":"UA",
      "language":"english",
      "genre":[  
         "kids",
         "adventure"
      ],
      "running_time":"120",
      "showtimes":[  
         {  
            "cinema_name":"Suncity",
            "display_showtime":"10:00 AM",
            "showtime_code":1000
         },
         {  
            "cinema_name":"PVR",
            "display_showtime":"1:00 PM",
            "showtime_code":1300
         }
      ]
   },
   {  
      "id":"2",
      "name":"Incredibles",
      "audience":"UA",
      "language":"english",
      "genre":[  
         "kids",
         "thriller"
      ],
      "running_time":"190",
      "showtimes":[  
         {  
            "cinema_name":"Suncity",
            "display_showtime":"8:00 AM",
            "showtime_code":0800
         },
         {  
            "cinema_name":"Suncity",
            "display_showtime":"2:00 PM",
            "showtime_code":1400
         }
      ]
   }
]
};

Iterating the first loop is working fine. Just want to loop through the items present in "showtimes" key.

My code:

var data = movies_list.movies;

for(var i = 0; i < data.length; i++){
   var fisrtLoopData = data[i];
   $('body').append('<p>'+ fisrtLoopData + '</p>');
}

Answers 1

  • movies_list.movies.forEach(function(movie) { 
        movie.showtimes.forEach(function(showtime) {
           console.log(showtime.cinema_name)
        });
    });
    

    in a functional way. You actually don't need any loops.


Related Articles