这是我的 json 文件的一部分
{
"articles": [
{
"rank": "1",
"title": "Harvard University",
"country": "USA",
"score": "100.00"
},
{
"rank": "3",
"title": "Massachusetts Institute of Technology",
"country": "USA",
"score": "97.12"
},
{
"rank": "5",
"title": "University of Oxford",
"country": "United Kingdom",
"score": "95.39"
},
{
"rank": "36",
"title": "École Polytechnique",
"country": "France",
"score": "59.09",
},
{
"rank": "904",
"title": "University of Basilicata",
"country": "Italy",
"score": "44.31",
}
]
}
我想计算具有用于制作谷歌图表的 JS 功能的相同国家/地区的数量。我需要这样的结果:
国家:{“美国”:57,“日本”:23,“英国”:38,“
另一个函数将返回分数大于 80 和小于 80 的大学的数量,如下所示:
分数:{“morethan80”:195,“lessthan80”:805,“
最佳答案
您需要做的是遍历您的 map 并检查它是否符合您的条件,如果符合,则增加它。
通常,reduce
接受一个数组作为输入并输出任何你想要的:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
const output = data.articles.reduce(
(result, article) => ({
country: {
...result.country,
[article.country]: result[article.country] ? result[article.country] + 1 : 1,
},
score: {
morethan80: parseInt(article.score) >= 80 ? result.morethan80 + 1 : result.morethan80,
lessthan80: parseInt(article.score) < 80 ? result.lessthan80 + 1 : result.lessthan80,
}
}),
{ country: {}, score: { morethan80: 0, lessthan80: 0 }}
);
如果您需要有关答案的更多详细信息,请告诉我。
关于javascript - 如何使用 JS 计算 json 文件中的相同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47100078/