0

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
2
  • Well you need to check if the id from the current genre element is the same as the current movie.genre_ids value … if(id == genre.id) { /* … */ } Commented Sep 11, 2019 at 10:03
  • 1
    If you can modify the structure of 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] */ } Commented Sep 11, 2019 at 10:06

3 Answers 3

0

You can simply do it unsing the forEach loop and using includes() method ,
Here is code snippet

var 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"
    }
  ];

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"}]



var arr = []
genres.forEach(function(singleObject){
    popularMovies.forEach(function(objectToMatch){
        if(objectToMatch.genre_ids.includes(singleObject.id)){
            arr.push(singleObject.name);
        }
    })
})
console.log(arr);

In arr you will have name off genres .
This will help you .

Sign up to request clarification or add additional context in comments.

7 Comments

when im using this with my state it return my state undefined but im logging it to console before the forEach and it has array in it don't know why it's reurning undefined
Can you tell me how your state syntax is . does it is as same as my var genre . Or tell me your how your state object looks so i update my code according to your state object . @NaveenKashyap
Or maybe try out by writing this.state.movies instead of popularMovies @NaveenKashyap
this is my state this.state={ genre:this.props.genres, popularMovies:this.props.popularMovies } replace genres with this.state.popularMovies but it's undefined
replace genres in forEach with this.state.genre And replace popularMovies with this.state.popularMovies . Try out by replacing this syntax . you will get Answer . @NaveenKashyap
|
0

You can do something like this:

let genres = [{
  "id": 28,
  "name": "Action"
},
{
  "id": 12,
  "name": "Adventure"
}]

I have a working example of code which returns all the matching genres name according to genre_ids

class TheTmdbApp extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            movies : [ {
                "popularity": 59.54,
                "vote_count": 792,
                "video": false,
                "poster_path": "\/8j58iEBw9pOXFD2L0nt0ZXeHviB.jpg",
                "id": 466272,
                "adult": false,
                "backdrop_path": "\/kKTPv9LKKs5L3oO1y5FNObxAPWI.jpg",
                "original_language": "en",
                "original_title": "Once Upon a Time in Hollywood",
                "genre_ids": [28, 35, 80, 18, 37],
                "title": "Once Upon a Time in Hollywood",
                "vote_average": 7.6,
                "overview": "A faded television actor and his stunt double strive to achieve fame and success in the film industry during the final years of Hollywood's Golden Age in 1969 Los Angeles.",
                "release_date": "2019-07-26"
            }, {
                "popularity": 45.265,
                "vote_count": 526,
                "video": false,
                "poster_path": "\/hgWAcic93phg4DOuQ8NrsgQWiqu.jpg",
                "id": 452832,
                "adult": false,
                "backdrop_path": "\/oOROXoQ402tHgK6NowmMUSLffkW.jpg",
                "original_language": "en",
                "original_title": "Serenity",
                "genre_ids": [9648, 53],
                "title": "Serenity",
                "vote_average": 5.2,
                "overview": "Baker Dill is a fishing boat captain leading tours off a tranquil, tropical enclave called Plymouth Island. His quiet life is shattered, however, when his ex-wife Karen tracks him down with a desperate plea for help.",
                "release_date": "2019-01-25"
            }, {
                "popularity": 50.454,
                "vote_count": 113,
                "video": false,
                "poster_path": "\/vOl6shtL0wknjaIs6JdKCpcHvg8.jpg",
                "id": 567609,
                "adult": false,
                "backdrop_path": "\/aNrNi5QExO6b8MnEGsfpgp21NIY.jpg",
                "original_language": "en",
                "original_title": "Ready or Not",
                "genre_ids": [27, 9648, 53],
                "title": "Ready or Not",
                "vote_average": 7.5,
                "overview": "A bride's wedding night takes a sinister turn when her eccentric new in-laws force her to take part in a terrifying game.",
                "release_date": "2019-08-21"
            }, {
                "popularity": 46.348,
                "vote_count": 2284,
                "video": false,
                "poster_path": "\/wgQ7APnFpf1TuviKHXeEe3KnsTV.jpg",
                "id": 447404,
                "adult": false,
                "backdrop_path": "\/nDP33LmQwNsnPv29GQazz59HjJI.jpg",
                "original_language": "en",
                "original_title": "Pokémon Detective Pikachu",
                "genre_ids": [28, 12, 14],
                "title": "Pokémon Detective Pikachu",
                "vote_average": 7,
                "overview": "In a world where people collect pocket-size monsters (Pokémon) to do battle, a boy comes across an intelligent monster who seeks to be a detective.",
                "release_date": "2019-05-10"
            }, {
                "popularity": 33.986,
                "vote_count": 45,
                "video": false,
                "poster_path": "\/vVYU0x9FRpiJNX7c54ciFnRBVYG.jpg",
                "id": 441282,
                "adult": false,
                "backdrop_path": "\/6rJAeP8xlq0bHUdCNg5epBvrFVa.jpg",
                "original_language": "en",
                "original_title": "Night Hunter",
                "genre_ids": [80, 9648, 53],
                "title": "Night Hunter",
                "vote_average": 6.1,
                "overview": "A police task force traps an online predator, only to discover that the depth of his crimes goes far beyond anything they had anticipated.",
                "release_date": "2019-09-06"
            }, {
                "popularity": 48.493,
                "vote_count": 1054,
                "video": false,
                "poster_path": "\/f4FF18ia7yTvHf2izNrHqBmgH8U.jpg",
                "id": 504608,
                "adult": false,
                "backdrop_path": "\/oAr5bgf49vxga9etWoQpAeRMvhp.jpg",
                "original_language": "en",
                "original_title": "Rocketman",
                "genre_ids": [18, 10402],
                "title": "Rocketman",
                "vote_average": 7.5,
                "overview": "The story of Elton John's life, from his years as a prodigy at the Royal Academy of Music through his influential and enduring musical partnership with Bernie Taupin.",
                "release_date": "2019-05-31"
            }, {
                "popularity": 46.85,
                "vote_count": 3,
                "video": false,
                "poster_path": "\/eU0orGizEpOli4wtN8HtfOOJDlA.jpg",
                "id": 516700,
                "adult": false,
                "backdrop_path": "\/nmHCKQ1GtlPLZVAtBfsYDqVPhPW.jpg",
                "original_language": "id",
                "original_title": "Gundala",
                "genre_ids": [28, 80, 18],
                "title": "Gundala",
                "vote_average": 8.2,
                "overview": "Sancaka has lived on the streets since his parents left him. Living a hard life, Sancaka survives by thinking about his own safety. When the condition of the city gets worse and injustice rages throughout the country, Sancaka must decide whether he continues to live to look after himself or rise to become their oppressed hero.",
                "release_date": "2019-08-29"
            }],
            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"
                    }
                ]

        }
    }

    getMovieGenreName(genre_ids){
        let genreIds = []
        let genreNames = []
        let genres = ""
        this.state.genres.forEach((genre,index) => {
            genreIds[index] = genre.id;
            genreNames[index] = genre.name;
        });
      
        genre_ids.forEach((genre) => {
            let genreIndex = genreIds.indexOf(genre);
            let genreName = genreNames[genreIndex];
            genres += genreName + ' . ';
        })
        genres = genres.slice(0, -2);
        return genres
    }

    render() {

        return (
            <div>
                {this.state.movies.map(movie => {

                    return (
                        <div>
                            <h4>{movie.title}</h4>
                            <span>Genres: {this.getMovieGenreName(movie.genre_ids)}</span>
                        </div>
                    )
                })}
            </div>
        )
    }
}

ReactDOM.render(<TheTmdbApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<body>
  <div id="app"></div>
</body>

Hope this helps, Happy Coding...!!!

7 Comments

it returns every movie name in single genre and it loops like so many times single genre variable have all movies in my array genre
if you need it for single movie object just pass that movie genre_ids to getMovieGenreName and you will get genres name of that movie.
in map it will pass only one movie genre_id or all of them cuz it's running 400 times
where it should be 1 movie genre there are all of movies genre
it will run for each movies in map
|
0
    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)=>{
        let genreList = []; 
        movie.popularity.genre_ids.map((id)=>{
            let find = genre.filter((el) => {
                return el.id === id
            });
            if (find.length > 0) {
                    genreList.push(find[0])
                }

        })
        console.log(genreList)      
        ))
    }
                 console.log(this.state.genre);
        });




      });

    }


    render() {
    return (
        <div>

        </div>
    )
    }
}

export default genre

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.