[Vuejs]-For-in cicle gives back only last result in array.push

0👍

Maybe there is a prettier way to do this, but this works. This will create a new array in the movies array, called genreNames, which will include the corresponding genre names.

const genres = [
  { id: 12, name: "Avventura" },
  { id: 16, name: "Animazione" },
  { id: 35, name: "Commedia" },
  { id: 80, name: "Crime" },
  { id: 99, name: "Documentario" },
  { id: 18, name: "Dramma" },
];

const movies = [
  { genre_ids: [12, 16], name: "Movie 1" },
  { genre_ids: [80, 99], name: "Movie 2" },
  { genre_ids: [18, 12, 99], name: "Movie 3" },
];

// our final result
let finalArray = [];
movies.map(element => {
  // create a temp array for the genres
  let genreNames = []
  element.genre_ids.map(genre => {
    // each genreid from the movie, find the corresponding name from the genres array
    genreNames.push(genres.find(val => val.id === genre).name)
  })
  // finally push the original movie and the newly create array for the names
  finalArray.push({ ...element, genreNames })
})
console.log(finalArray);

Leave a comment