Search code examples
javascriptjqueryarraysapiitems

Getting the last Api data from a array


I have a covid 19 Api in my site, but i want it to give only the last data, every day the array keeps getting bigger, how do i fix this?

// 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);


});

This is how the array will form: Picture of RAW Api data


Solution

  • just select the latest value of the array

    // 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[data.length-1].Confirmed;
        var covid_active = data[data.length-1].Active;
        var covid_deaths = data[data.length-1].Deaths;
        var covid_date = data[data.length-1].Date;
    
      // Make the variable an working variable for in html
      $("#confirmed").text(`confirmed: ${covid_confirmed}`);
      $("#active").text(`active: ${covid_active}`);
      $("#deaths").text(`deaths: ${covid_deaths}`);
      $("#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>