Skip to content
Advertisement

Filter nested obejct

So I have this function that in theory should filter an array of movies by a given genre, but i get this error:

TypeError: movie.genres.some is not a function.
(in 'movie.genres.some(function(item){return item.name === genre;})',
'movie.genres.some' is undefined) `
Movie class =>  
  title: string,
  ...,
  genres: Genre[]

Genre class => 
  id: number,
  name: string
FilterMovies = (genre: string) => {
  let fmovies: Movie[] = this.state.movies.filter((movie) => {
    let data = movie.genres.some((item) => item.name === genre);
    return data;
  });

Am I doing this stuff right or did i mess up one of the functions? Any help would be very much appreciated!

edit: here’s an example of a movie object enter image description here

Advertisement

Answer

as some comments suggested, i was able to solve the problem with the following:

  • found out my object wasn’t an array so i used Object.values to get the collections values
  • i made sure to check if every movie has a genre object that is not null nor undefined

although it probably still isn’t perfect yet it works as of now so here it is:

FilterMovies = (genre: string) => {

let fmovies: Movie[] = this.state.movies.filter((movie) => {
  let genreObj;
  movie.genres != null || typeof movie.genres !== "undefined"
    ? (genreObj = Object.values(movie.genres))
    : null;
  let genreNames: string[] = [];

  genreObj != null || typeof genreObj !== "undefined"
    ? genreObj?.forEach((genre) => {
        genreNames.push(genre.name);
      })
    : null;

  let data = genreNames.some((item) => item === genre);
  return data;
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement