如何在页面上获取后对数组中的项目进行排序和获取(Discord V12)

我试图获得 covid 案例最多的前 5 个国家/地区,但是当我尝试为此调整另一个代码时,出现错误。


 fetch("https://pomber.github.io/covid19/timeseries.json")

 .then(response => response.json())

 .then(data => {

var countryArr = Object.keys(data).map(i => i);

                countryArr.forEach((country) => {

                let countryData = data[country];

                countryData = countryData[countryData.length - 1];

                })

                

                let countries = getCovidRank(countryArr, message)

                countries.map((countryData, index) => {

                    countries[index] = `\\🔹 #${index+1} | **Country**: \`\`${countryData[0]}\`\` | **Confirmed**: \`\`${countryData[0].confirmed}\`\``

                    })


//The rest of the code will always work, the problem is up there


}

这是 getCovidRank 文件:


getCovidRank: (countryArr, message) => {

        let countryList = []


        for(var country in countryArr) {

           let countryData = countryArr.confirmed 

           countryList.push([countryArr, (countryData[country])])

        }

        

        countryList.sort((countryData1, countryData2) => {

            return countryData2[1] - countryData1[1] || countryData2[2] - countryData1[2]

        })

        return countryList;

        

    }

我真的希望你能帮助我,我正在努力学习如何做到这一点。下面的代码显示了全局情况(这段代码很好):


            var worldStats = { confirmed: 0, recovered: 0, deaths: 0 };

            var countryArr = Object.keys(data).map(i => i);

            countryArr.forEach((country) => {

            let countryData = data[country];

            // pick last object for today data

                countryData = countryData[countryData.length - 1];

                worldStats.confirmed += countryData.confirmed;

                worldStats.recovered += countryData.recovered;

                worldStats.deaths += countryData.deaths;

            });




动漫人物
浏览 100回答 1
1回答

PIPIONE

这是一个非常简单的演示,按确认状态显示前 5 个国家。编辑刚刚添加了一个工作片段function init() {&nbsp; fetch("https://pomber.github.io/covid19/timeseries.json")&nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; .then(data => {&nbsp; &nbsp; &nbsp; var countries = [];&nbsp; &nbsp; &nbsp; Object.keys(data).forEach(country => {&nbsp; &nbsp; &nbsp; &nbsp; var total = data[country].reduce(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (acc, val) => (acc += val.confirmed),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; countries.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: country,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; confirmed: total&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; countries.sort((a, b) => a.confirmed > b.confirmed ? -1 : 1);&nbsp; &nbsp; &nbsp; document.getElementById('div').innerHTML = countries.slice(0, 5).map(c => c.name + ' ' + c.confirmed).join('<br>');&nbsp; &nbsp; })}init();<div id="div"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript