Home > Enterprise >  Multiple Fetch with arrays into response
Multiple Fetch with arrays into response

Time:02-02

I'm student now trying multiple fetch req with diff endpoints (themoviedb API).

//to get movie list
fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=' key '&language=' lang).then(resp=> resp.json())
//data
results: [
      {
        adult: false,
        backdrop_path: '/faXT8V80JRhnArTAeYXz0Eutpv9.jpg',
        genre_ids: [ 16, 28, 12, 35, 10751, 14 ],
        id: 315162,
        original_language: 'en',
        original_title: 'Puss in Boots: The Last Wish',
        overview: "Secuela de 'El gato con botas' (2011). El Gato con Botas descubre que su pasión por la aventura le ha pasado factura: ha consumido ocho de sus nueve vidas, por ello emprende un viaje épico para encontrar el mítico Último Deseo y restaurar sus nueve vidas...",
        popularity: 5032.178,
        poster_path: '/lyP4WNmUiiOgl4g2z7ywE0z6SGF.jpg',
        release_date: '2022-12-07',
        title: 'El Gato con Botas: El último deseo',
        video: false,
        vote_average: 8.6,
        vote_count: 3032
      },
]

now to get list of genres

fetch('https://api.themoviedb.org/3/genre/movie/list?api_key=' key '&language=' lang).then(resp=>resp.json())

//data
[
{ id: 28, name: 'Acción' },
{ id: 28, name: 'Acción' },
{ id: 12, name: 'Aventura' },
{ id: 16, name: 'Animación' },
{ id: 35, name: 'Comedia' },
{ id: 80, name: 'Crimen' },
{ id: 99, name: 'Documental' },
{ id: 18, name: 'Drama' },
{ id: 10751, name: 'Familia' },
{ id: 14, name: 'Fantasía' },
{ id: 36, name: 'Historia' },
{ id: 27, name: 'Terror' },
{ id: 10402, name: 'Música' },
{ id: 9648, name: 'Misterio' },
{ id: 10749, name: 'Romance' },
{ id: 878, name: 'Ciencia ficción' },
{ id: 10770, name: 'Película de TV' },
{ id: 53, name: 'Suspense' },
{ id: 10752, name: 'Bélica' },
{ id: 37, name: 'Western' }
]

How can i replace genre_ids content for each film (first fetch) with the name of the corresponding id in 2nd fetc? thanks in advance. I want return a template with all data of movie but for now i only can show id of genre

CodePudding user response:

Luckily, for that you have a one-liner at your disposal:

let genres = [
{ id: 28, name: 'Acción' },
{ id: 28, name: 'Acción' },
{ id: 12, name: 'Aventura' },
{ id: 16, name: 'Animación' },
{ id: 35, name: 'Comedia' },
{ id: 80, name: 'Crimen' },
{ id: 99, name: 'Documental' },
{ id: 18, name: 'Drama' },
{ id: 10751, name: 'Familia' },
{ id: 14, name: 'Fantasía' },
{ id: 36, name: 'Historia' },
{ id: 27, name: 'Terror' },
{ id: 10402, name: 'Música' },
{ id: 9648, name: 'Misterio' },
{ id: 10749, name: 'Romance' },
{ id: 878, name: 'Ciencia ficción' },
{ id: 10770, name: 'Película de TV' },
{ id: 53, name: 'Suspense' },
{ id: 10752, name: 'Bélica' },
{ id: 37, name: 'Western' }
]
let movies = [
      {
        adult: false,
        backdrop_path: '/faXT8V80JRhnArTAeYXz0Eutpv9.jpg',
        genre_ids: [ 16, 28, 12, 35, 10751, 14 ],
        id: 315162,
        original_language: 'en',
        original_title: 'Puss in Boots: The Last Wish',
        overview: "Secuela de 'El gato con botas' (2011). El Gato con Botas descubre que su pasión por la aventura le ha pasado factura: ha consumido ocho de sus nueve vidas, por ello emprende un viaje épico para encontrar el mítico Último Deseo y restaurar sus nueve vidas...",
        popularity: 5032.178,
        poster_path: '/lyP4WNmUiiOgl4g2z7ywE0z6SGF.jpg',
        release_date: '2022-12-07',
        title: 'El Gato con Botas: El último deseo',
        video: false,
        vote_average: 8.6,
        vote_count: 3032
      },
]
for (let movie of movies) {
    movie.genres = genres.filter((item) => ((movie.genre_ids.indexOf(item.id) >= 0)));
    movie.genre_names = movie.genres.map(item => item.name);
}
console.log(movies);

Explanation:

  • genres
    • we use the filter function that returns a subset of the array of items that meet the criteria
    • the criteria is that the id is among the ids of our expectation
  • genre_names:
    • we use the map function to get only the names

I was not sure whether you want only the names or the names along with their ids, so we have both, you can restrict the results according to your liking.

Note that we loop movies and perform the same logic for each movie.

CodePudding user response:

You can use an async function to make it easier to perform multiple fetches. Use Array#find to get the corresponding genre from the other array.

async function getData() {
    const movieList = await (await fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=' key '&language=' lang)).json();
    const genreList = await (await fetch('https://api.themoviedb.org/3/genre/movie/list?api_key=' key '&language=' lang)).json();
    for (const movie of moveList.results)
        movie.genre_ids = movie.genre_ids.map(id => genreList.find(g => g.id === id)?.name);
}

CodePudding user response:

The getNowPlayingWithGenres (async) function below will return a list of current movies sorted by their title and includes a list of human-readable genres.

Note: Just make sure to set the API key.

const
  apiUrl = 'https://api.themoviedb.org/3',
  apiKey = '<API_KEY>',
  lang   = 'en-US';

const getGenresIdMap = async () => {
  const
    res = await fetch(`${apiUrl}/genre/movie/list?api_key=${apiKey}&language=${lang}`),
    { genres } = await res.json();
  return genres.reduce((map, { id, name }) => map.set(id, name), new Map);
};

const getNowPlaying = async () => {
  const
    res = await fetch(`${apiUrl}/movie/now_playing?api_key=${apiKey}&language=${lang}`),
    { results } = await res.json();
  return results;
};

const getNowPlayingWithGenres = async () => {
  const
    genreIdMap = await getGenresIdMap(),
    nowPlaying = await getNowPlaying();
  return nowPlaying
    .map(({ title, genre_ids }) =>
      ({ title, genres: genre_ids.map(id => genreIdMap.get(id)).sort() }))
    .sort((a, b) => a.title.localeCompare(b.title));
}

(async() => {
  const result = await getNowPlayingWithGenres();
  console.log(result);
})();
.as-console-wrapper { top: 0; max-height: 100% !important; }

  • Related