0

I'm doing an activity with JavaScript where I must call an extern API and get the information that it contains, the JSON file structure is the next:

"dates": {
    "2020-03-22": {
        "countries": {

The problems is that when I get the information I put it in a variable named 'info' and to arrive to the date camp I have put the date text in another variable to concatenate with the previous object, but the problem is that returns 'undefined' value.

Here's the code I made to get the information:

function callAPI() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200){
            var info = JSON.parse(this.responseText);
            var dateApi = "2020-03-22";

            console.log(info.dates.dateApi);
        }
    }
    xmlhttp.open("GET", "https://api.covid19tracking.narrativa.com/api/2020-03-22/country/spain");
    xmlhttp.send();
}
  • You need `info.dates[dateApi]` so the value is used instead of the literal "dateApi" key. –  Dec 13 '21 at 11:47
  • Duplicate: [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) –  Dec 13 '21 at 11:48

1 Answers1

0

Change info.dates.dateApi code to info.dates[dateApi] this should work

function callAPI() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200){
            var info = JSON.parse(this.responseText);
            var dateApi = "2020-03-22";

            console.log(info.dates[dateApi]);
        }
    }
    xmlhttp.open("GET", "https://api.covid19tracking.narrativa.com/api/2020-03-22/country/spain");
    xmlhttp.send();
}
Akhilraj R
  • 69
  • 5