这是我的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",
}
]
}
我想计算用于制作Google图表的JS功能的相同国家/地区的数量。我需要这样的结果:
country:{"USA" : 57,"Japan" : 23,"United Kingdom" : 38,"
另一个函数将返回分数大于80且小于80的大学的数量,如下所示:
score:{"morethan80" : 195,"lessthan80" : 805,"
最佳答案
您需要做的是遍历地图,检查是否符合您的条件,如果符合,则增加它。
通常,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/