javascript - 如何返回一个对象数组,每个对象有多少个计数
问题描述
我将如何返回一个返回 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);
解决方案
您可以以集合的形式使用白名单,并将每个对象以及该对象内的每个流派减少为每首歌曲流派的计数:
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)
推荐阅读
- unity3d - 在 Vuforia 中,检测到了我的图像目标。我的笔记本电脑上一切正常,但我的 Android 上的 GameObject 是粉红色的
- javascript - 我可以从 NodeJs 服务器访问网页上的网络流量数据吗?
- ios - iOS 系统库即使不添加到“框架、库和嵌入式内容”也可以导入
- r - 仅使用 Signif 提取变量和系数。R 小于 0.05
- javascript - Webpack 文件加载器未在生产构建中加载资产文件夹
- ruby-on-rails - Ruby graphql 如何定义不是 Active Record 的对象类型?
- git - 为什么我的 Git 无法通过终端进行更新?
- firebase - 实时数据库是否具有像 ServerValue.increment 这样的 Flutter 原子增量方法?
- firebase - Flutter RealtimeDatabase ServerValue.Increment
- javascript - 如何使用选项作为参数初始化hammerJS对象