I am trying to get the details of the the movie using tmdb api so fall everything was good until i tried to display all the genres of that movie
const tmdb_api_url = "https://api.themoviedb.org/3/tv/" + 127332 + "?api_key=API-KEY"; async function getDetails() { const response = await fetch (tmdb_api_url); const data = await response.json(); const { name, first_air_date, vote_average, number_of_seasons, episode_run_time, genres, overview, origin_country} = data; document.getElementById('title').textContent = name; document.getElementById('first_air_date').textContent = first_air_date; document.getElementById('vote_average').textContent = vote_average; document.getElementById('number_of_seasons').textContent = number_of_seasons + " Season" + (number_of_seasons == 1 ? "" : "s "); document.getElementById('run_time').textContent = episode_run_time; document.getElementById('overview').textContent = overview; document.getElementById('origin_country').textContent = origin_country; var g = ""; for (i in genres) { g += genres[i].name; } document.getElementById('genres').textContent = genres[i].name; } getDetails();
This is what i tried but its only showing one genre
And can anyone help me simplify the code what i tried
Advertisement
Answer
You are getting only one genre because of this line document.getElementById('genres').textContent = genres[i].name;
This will always display the last genre.
Modify it as follows
var g = ""; for (i in genres) { g += genres[i].name + ", "; } document.getElementById('genres').textContent = g.substr(0, g.length - 1); // to remove last , added
Update : Adding each genre in there respective anchor tag
let genreTags = ""; for(i in genres){ genreTags+= `<a href="${genre_link}">${genres[i].name}</a>`; // Add genre link in the href } document.getElementById("genres").innerHTML = genreTags;
This is the jist of adding genres as anchor, but there are much better ways of doing it.