我有一个很大的json,里面有两个数组“genres”和“movies”,json的一部分看起来像这样:
{
"genres": [
"Comedy",
"Fantasy",
"Crime",
"Drama",
"Music",
"Adventure",
"History",
"Thriller",
"Animation",
],
"movies": [
{
"id": 1,
"title": "Beetlejuice",
"year": "1988",
"runtime": "92",
"genres": [
"Comedy",
"Fantasy"
],
"director": "Tim Burton",
"actors": "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page",
"plot": "A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.",
"posterUrl": "https://m.media-amazon.com/images/M/MV5BZDdmNjBlYTctNWU0MC00ODQxLWEzNDQtZGY1NmRhYjNmNDczXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_FMjpg_UX1000_.jpg"
},
{
"id": 2,
"title": "The Cotton Club",
"year": "1984",
"runtime": "127",
"genres": [
"Crime",
"Drama",
"Music"
],
"director": "Francis Ford Coppola",
"actors": "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee",
"plot": "The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.",
"posterUrl": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"
},
{
"id": 3,
"title": "The Shawshank Redemption",
"year": "1994",
"runtime": "142",
"genres": [
"Crime",
"Drama"
],
"director": "Frank Darabont",
"actors": "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler",
"plot": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",
"posterUrl": "https://m.media-amazon.com/images/M/MV5BMTQ1ODM2MjY3OV5BMl5BanBnXkFtZTgwMTU2MjEyMDE@._V1_.jpg"
},
和其他143部电影。
我需要找出有多少类型的电影都使用“genres”数组中的“movies”数组。
我做了这个代码:
const comedy = props.movies.map(movie => movie.genres.filter(genre => genre === "Comedy").length)
.reduce((total, count) => total + count, 0);
const fantasy = props.movies.map(movie => movie.genres.filter(genre => genre === "Fantasy").length)
.reduce((total, count) => total + count, 0);
const crime = props.movies.map(movie => movie.genres.filter(genre => genre === "Crime").length)
.reduce((total, count) => total + count, 0);
我还为其他18种音乐类型制作了这首歌。
我可以做这个代码更短?Thnx
2条答案
按热度按时间deyfvvtc1#
下面是一个只对电影迭代一次的解决方案(如果电影没有在其
genres
数组中声明重复的流派,则此解决方案有效)67up9zun2#
非常简单,因为你在同一个对象中有一个流派列表:
这将导致类似于
供参考,来自条目:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
见下面的例子(我已经从电影中删除了额外的未使用的属性,以提高可读性)