I want to display the genre of each movie in the UI, I am mapping through an array of objects that looks like this:
const movies = [
{
vote_count: 294,
id: 439079,
video: false,
vote_average: 6.1,
title: "The Nun",
popularity: 245.792,
poster_path: "/sFC1ElvoKGdHJIWRpNB3xWJ9lJA.jpg",
original_language: "en",
original_title: "The Nun",
genre_ids: [27, 9648, 53],
backdrop_path: "/fgsHxz21B27hOOqQBiw9L6yWcM7.jpg",
adult: false
},
{
vote_count: 7962,
id: 299536,
video: false,
vote_average: 8.3,
title: "Avengers: Infinity War",
popularity: 210.234,
poster_path: "/7WsyChQLEftFiDOVTGkv3hFpyyt.jpg",
original_language: "en",
original_title: "Avengers: Infinity War",
genre_ids: [12, 878, 28],
backdrop_path: "/lmZFxXgJE3vgrciwuDib0N8CfQo.jpg",
adult: false
},
{
vote_count: 87,
id: 346910,
video: false,
vote_average: 5.6,
title: "The Predator",
popularity: 165.197,
poster_path: "/wMq9kQXTeQCHUZOG4fAe5cAxyUA.jpg",
original_language: "en",
original_title: "The Predator",
genre_ids: [27, 878, 28],
backdrop_path: "/x0VXCWSTny5JRvpgDnw5ptwQyhA.jpg",
adult: false
}
];
As you can see, each object has an array of genres_ids, so I am just displaying numbers (for each item, the one with index of 0, so the first id) I also have another array of objects listing all genres and its corresponding id:
const genres = [
{ id: 28, name: "Action" },
{ id: 12, name: "Adventure" },
{ id: 16, name: "Animation" },
{ id: 35, name: "Comedy" },
{ id: 80, name: "Crime" },
{ id: 99, name: "Documentary" },
{ id: 18, name: "Drama" },
{ id: 10751, name: "Family" },
{ id: 14, name: "Fantasy" },
{ id: 36, name: "History" },
{ id: 27, name: "Horror" },
{ id: 10402, name: "Music" },
{ id: 9648, name: "Mystery" },
{ id: 10749, name: "Romance" },
{ id: 878, name: "Science Fiction" },
{ id: 10770, name: "TV Movie" },
{ id: 53, name: "Thriller" },
{ id: 10752, name: "War" },
{ id: 37, name: "Western" }
];
My solution to display the genre name of each movie is as followed:
const getGenres = movies.map(movie => {
if (movie.genre_ids[0] === 12) return "Adventure"
else if (movie.genre_ids[0] === 27) return "Horror"
else if (movie.genre_ids[0] === 28) return "Action"
});
This works, but I am sure there must be a better way to do this, it feels odd having to write one condition for each genre. If this was an array of 500 items, then my solution is no longer viable. How can I achieve the same result using a more viable code? @camperextraordinaire @gunhoo93
I tried something like this:
const getGenres = movies.map(movie => {
for (let i = 0; i < movies.length; i++) {
if (movie.genre_ids[0] === genres[i].id) return genres[i].name
}
});
But I am getting undefined in index 0 and 2, not sure why.