开发者

How do you group an array of movie objects based on their genre?

开发者 https://www.devze.com 2022-12-07 22:11 出处:网络
I have an array of movies that have multiple genres. Using React, what is the best way to loop through that array of objects and group them by genre?

I have an array of movies that have multiple genres. Using React, what is the best way to loop through that array of objects and group them by genre?

Desired Output:

  • Action
    • Movie 1
    • Movie 2
    • Movie 5
  • Crime
    • Movie 1
    • Movie 4
  • Drama
    • Movie 1
    • Movie 3
    • Movie 4
  • Horror
    • Movie 3
    • Movie 5
import _ from 'lodash'

const movieList = [
  {
    "genres": ["Action","Crime","Drama"],
    "title": "Movie 1"
  },
  {
    "genres": ["Action","Comedy"],
    "title": "Movie 2"
  },
  {
    "genres": ["Drama","Horror"],
    "title": "Movie 3"
  },
  {
    "genres": ["Crime","Drama"],
    "title": "Movie 4"
  },
  {
    "genres": ["Action","Crime","Horror"],
    开发者_如何转开发"title": "Movie 5"
  }
]

export default function Home() {
  const [movies, setMovies] = useState(movieList)
  
  return (
    // return movies listed by genre
  )
}


Transforming data like this is what .reduce is for:

movieList.reduce((acc, curr) => {
  curr.genres.forEach(genre => acc[genre] ? acc[genre].push(curr.title) : acc[genre] = [curr.title]);
  return acc;
}, {});
0

精彩评论

暂无评论...
验证码 换一张
取 消