TransWikia.com

How to get a specific name from another array by its id?

Stack Overflow Asked by Ahmed Eid on November 27, 2021

How to get the name of the genre by its id from another array? I’ve tried calling .find on the genres
array but it says undefined

 const movies = [ 
  {movieName: blank, id: 1, genre_ids: [5,6,7]}, 
  ...more movies
  ]
const genres = [
       {id:5, name: 'action'}, 
       {id:6, name: 'comedy'},  
       {id:7, name: 'horror'}
 ]


movies.map((movie) => <Movie title={movie.movieName} key={movie.id} genre={???}/>

One Answer

Hope this will help you.

const movies = [ 
  {movieName: 'blank', id: 1, genre_ids: [5,6,7]}, 
  {movieName: 'move 2', id: 2, genre_ids: [5,7]}
  ]
const genres = [
       {id:5, name: 'action'}, 
       {id:6, name: 'comedy'},  
       {id:7, name: 'horror'}
 ]


movies.map((movie) => console.log(
movie.genre_ids.flatMap(g => 
  genres.filter(genre => genre.id === g)
  .map(r => r.name)
  )
 )
)

Answered by Eric on November 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP