这是我的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功能的相同国家/地区的数量来制作Google图表。我需要这样的结果:
country:{"USA" : 57,"Japan" : 23,"United Kingdom" : 38,"
另一个函数将返回分数大于80且小于80的大学数量,如下所示:
score:{"morethan80" : 195,"lessthan80" : 805,"
答案 0 :(得分:3)
你需要做的是循环你的地图,检查它是否符合你的条件,如果是,就增加它。
通常情况下,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 }}
);
告诉我你是否需要更多关于答案的细节。