i have a array of ids in every object in array of object, and I want to use a for loop to match those ids in a second array of object ids and return that object name from second array, but i'm unable to use a for loop and if statement. I want to render those names in HTML.
This is what my genres array looks like:
"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"
}
]
This is what my popular movies object looks like. I want to loop through genre_ids to genres, and if match any of genre ids with the ids of genre_ids i want to save the name of genre name:
popularMovies=[{
"popularity": 507.672,
"vote_count": 224,
"video": false,
"poster_path": "/zfE0R94v1E8cuKAerbskfD3VfUt.jpg",
"id": 474350,
"adult": false,
"backdrop_path": "/4W0FnjSGn4x0mKZlBRx8OjFxQUM.jpg",
"original_language": "en",
"original_title": "It Chapter Two",
"genre_ids": [
35,
27
],
"title": "It Chapter Two",
"vote_average": 7.2,
"release_date": "2019-09-06"}]
these arrays are in state
import React, { Component } from 'react'
import store from '../../store'
export class genre extends Component {
constructor(props){
super(props)
this.state={
genre:[],
popularMovies:[],
}
store.subscribe(() => {
// When state will be updated(in our case, when items will be fetched),
// we will update local component state and force component to rerender
// with new data.
this.setState({
popularMovies: store.getState().popularMovies.movies,
genre:store.getState().genresIds.genreIds
},()=>{
if (!this.state.genre ) {
return;
}
this.state.popularMovies.map((movie)=>(
movie.genre_ids.map((id)=>(
this.genre.map((genre)=>(
console.log(id,genre)
//how do i match genre_ids id with genre id
))
))
))
}
console.log(this.state.genre);
});
});
}
render() {
return (
<div>
</div>
)
}
}
export default genre
movie.genre_idsvalue …if(id == genre.id) { /* … */ }genres, you could use the ID as “key” / property name - then you don’t need the inner loop, but you could simply check if the property matching the id is set."genres": { "28": "Action", "12": "Adventure", …},if(this.genre[id]) { /* do something with this.genre[id] */ }