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;
}, {});
精彩评论