我怎样才能计算与JS的json文件相同的值
这是我的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", } ] }
我想统计与谷歌图表的JSfunction相同的国家的数量。 我需要这样的结果: country:{"USA" : 57,"Japan" : 23,"United Kingdom" : 38,"
而另一个函数将会返回分数大于80且小于80的大学数,如下所示: score:{"morethan80" : 195,"lessthan80" : 805,"
你需要做的是循环浏览地图,检查它是否符合你的条件,如果是的话,增加它。
通常, reduce
可以在input和输出中使用任何数组: 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 }} );
告诉我,如果你需要更多的答案细节。