I want to add genre to my Movie Search app's carousel using map function. I have two json files one of them is an array of movie data as objects having a key as genre_ids eg:
genre_ids: 0: 16 1: 28 2: 12 3: 35 4: 10751 5: 14
and other contains an array of objects specifying the name of the genre with a unique key. eg:
{ "genres": [ { "id": 10759, "name": "Action & Adventure" } ] }
The Json files:
I tried mapping the json with movie data first. Then while mapping the genre i checked if the id of the genre matches with that of the id of the movie data element. Then I returned the name of that particular genre. But it is returning the names of all the genre present in the genre json.
My code:
{
trend.map((e, i) => {
return (
<div className="carousel-item" key={i}>
<img
src={`${img}${e.backdrop_path}`}
className="d-block carimage" alt="..." />
<div className="carousel-caption d-none d-md-block">
<div className='caro-discription'>
<button className='trailer-main-button'>More Info!!</button>
<h1>{e.title?e.title:e.name}</h1>
<h3>Rating: {e.vote_average}/10</h3>
</div>
<div className='genre-list'>
{genre.map((a,b)=>{
return(
<h3 className='genre-list-item' key={b}>{a.id=e.genre_ids? a.name: null}</h3>
)
})}
</div>
</div>
</div>
)
})
}
There are a couple of things you're doing wrong here. First is the use of map
instead of find
. Your Movie
object has one genre_ids
property which is always a positive integer. This means what you don't need to map all genres which match the genre_ids
, instead you just need to find the specific genre
your movie is tagged as:
<h3 key={e.genre_ids * e.id}>{genres.find((g, idx) => g.id === e.genre_ids).name}</h3>
If you do have multiple genres, then you'd use map:
{genres.map((g, idx) => e.genre_ids.includes(g.id) ? <h3 key={e.id * g.id}>{g.name}</h3> : null )}
This way you save processing time.
Also, your code has the issue of using =
for comparison. A single equals sign is used for assignment. If you want to check equality between two values, you'd use ==
. If you want to check if the two are of the same type
as well, you'd use ===
.