首页 > 解决方案 > 如何返回一个对象数组,每个对象有多少个计数

问题描述

我将如何返回一个返回 Country、Rock 和 Pop 流派的对象,并计算每种流派的歌曲数量?输出看起来像:

国家:4,摇滚:2,流行:1

const music=  [{
     "title": "Cheats",
     "year": 2018,
     "cast": ["Jane Rhee", "Kacey Brown"],
     "genres": ["Country"]
 }, {
     "title": "Road",
     "year": 2018,
     "cast": ["Jeff Bates", "Alan Walker", "Cindy Bates"],
     "genres": ["Country"]
 }, {
     "title": "Trail Down",
     "year": 2018,
     "cast": ["Ken Clemont"],
     "genres": ["Jazz"]
 }, {
     "title": "Way Down",
     "year": 2018,
     "cast": ["Denzel Harr", "Dan Smith", "Lee Kyle", "Nate Hill"],
     "genres": ["Pop"]
 }, {
     "title": "Fountain",
     "year": 2018,
     "cast": ["Brad Smith", "Rosa King"],
     "genres": ["Rock"]
 }, {
     "title": "Gold Bells",
     "year": 2018,
     "cast": ["Paisley John"],
     "genres": ["Blues"]
 }, {
     "title": "Mountain Curve",
     "year": 2018,
     "cast": ["Michael Johnson"],
     "genres": ["Country"]
 }, {
     "title": "Arabella",
     "year": 2018,
     "cast": [],
     "genres": ["Rock"]
 }, {
     "title": "Curved",
     "year": 2018,
     "cast": ["Brett Shay"],
     "genres": ["Country"]
 }];

这是我的代码。我得到了所有的流派,没有计数。

let songs = []; 

for (var i = 0; i < music.length; i++) {
    songs.push(music[i].genres);
}
    console.log(songs);

标签: javascriptarraysjsonfilter

解决方案


您可以以集合的形式使用白名单,并将每个对象以及该对象内的每个流派减少为每首歌曲流派的计数:

const music = [
  { title: 'Cheats', year: 2018, cast: ['Jane Rhee', 'Kacey Brown'], genres: ['Country'] },
  { title: 'Road', year: 2018, cast: ['Jeff Bates', 'Alan Walker', 'Cindy Bates'], genres: ['Country'] },
  { title: 'Trail Down', year: 2018, cast: ['Ken Clemont'], genres: ['Jazz'] },
  { title: 'Way Down', year: 2018, cast: ['Denzel Harr', 'Dan Smith', 'Lee Kyle', 'Nate Hill'], genres: ['Pop'] },
  { title: 'Fountain', year: 2018, cast: ['Brad Smith', 'Rosa King'], genres: ['Rock'] },
  { title: 'Gold Bells', year: 2018, cast: ['Paisley John'], genres: ['Blues'] },
  { title: 'Mountain Curve', year: 2018, cast: ['Michael Johnson'], genres: ['Country'] },
  { title: 'Arabella', year: 2018, cast: [], genres: ['Rock'] },
  { title: 'Curved', year: 2018, cast: ['Brett Shay'], genres: ['Country'] }
]

const set = new Set(['Country', 'Rock', 'Pop'])
const count = music.reduce((a, o) => (o.genres.forEach(g => (set.has(g) ? (a[g] = (a[g] || 0) + 1) : null)), a), {})

console.log(count)


推荐阅读