猿问

从数组中获取最后的 Api 数据

我的网站上有一个 covid 19 Api,但我希望它只提供最后的数据,数组每天都在变大,我该如何解决这个问题?


// Api Link+Key

$.getJSON("https://api.covid19api.com/total/country/netherlands", 


// Function to extract data from the Api

function(data){

    console.log(data);


// connect a variable to the Api Path

    var covid_confirmed = data[231].Confirmed;

    var covid_active = data[231].Active;

    var covid_deaths = data[231].Deaths;

    var covid_date = data[231].Date;


// Make the variable an working variable for in html

$('.covid_confirmed').append(covid_confirmed);

$('.covid_active').append(covid_active);

$('.covid_deaths').append(covid_deaths);

$('.covid_date').append(covid_date);



});

这就是数组的形成方式: 原始 Api 数据的图片


饮歌长啸
浏览 119回答 3
3回答

繁花如伊

只需选择数组的最新值// Api Link+Key$.getJSON("https://api.covid19api.com/total/country/netherlands",&nbsp;// Function to extract data from the Apifunction(data){&nbsp; &nbsp; console.log(data);// connect a variable to the Api Path&nbsp; &nbsp; var covid_confirmed = data[data.length-1].Confirmed;&nbsp; &nbsp; var covid_active = data[data.length-1].Active;&nbsp; &nbsp; var covid_deaths = data[data.length-1].Deaths;&nbsp; &nbsp; var covid_date = data[data.length-1].Date;&nbsp; // Make the variable an working variable for in html&nbsp; $("#confirmed").text(`confirmed: ${covid_confirmed}`);&nbsp; $("#active").text(`active: ${covid_active}`);&nbsp; $("#deaths").text(`deaths: ${covid_deaths}`);&nbsp; $("#date").text(`date: ${covid_date}`);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="confirmed"></div><div id="active"></div><div id="deaths"></div><div id="date"></div>

茅侃侃

covid19api.com 的官方文档显示,您可以在 API 调用中添加一个fromand - 参数。to这使您可以指定仅需要自给定日期以来的数据,因此您可以使用调用$.getJSON("https://api.covid19api.com/total/country/netherlands/status/confirmed?from=2020-09-08T23:00:00Z&to=2020-09-09T00:00:00Z")仅获取一个包含 2020 年 9 月 9 日数据的数组元素

Qyouu

您可以获得最后一条记录。const&nbsp;lastRecord&nbsp;=&nbsp;data.pop(); or const&nbsp;lastRecord&nbsp;=&nbsp;data[data.length-1];你为什么不为你的 api 提供排序和分页选项?另一种解决方案是为最后一份报告创建一条路线,比如/latest-result
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答