Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill dropdown with json data from restful api using vanilla js

I want to fill dropdown menu with dates from this API

    // Create Asynchronous function to grab the data for filling dropdown
async function getData() {
  try {
    // We are using fetch to get the response
    const response = await fetch('http://194.141.118.43:3010/dates');
    const data = await response.json();

    // Trigger the listData function and pass the result
    listDataDates(data);
  } catch (error) {
    console.log(error);
  }
}

// Create a function that will insert the data into our legends UL in dropdown
function listDataDates(data) {
  // Loop through each result and append the data.
  data.map(function (clickedDates) {
    const fillDates = `
    <li><a class="dropdown-item" href="#">${clickedDates.dataprog}</a></li>`;
    const item = document.createElement('li');
    item.innerHTML = fillDates;
    list.appendChild(item);
  });
  // Finally append all the data to the UL.
  ulDates.appendChild(list);
}

I try like that but I receive message error: TypeError: data.map is not a function

How can I populate the menu with the data with dataprog values from the API ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

clickedDates.dataprog

not working, what should I put in its place ?

When I use:

console.log(JSON.stringify(data, null, 2))

at the beginning of the function listDataDates I see in the console this data:

    {
  "floodguard_dates": {
    "command": "SELECT",
    "rowCount": 6,
    "oid": null,
    "rows": [
      {
        "datprog": "2023-01-20T07:00:00.000Z"
      },
      {
        "datprog": "2023-01-20T06:00:00.000Z"
      },
      {
        "datprog": "2023-01-19T19:00:00.000Z"
      },
      {
        "datprog": "2023-01-19T07:00:00.000Z"
      },
      {
        "datprog": "2023-01-18T07:00:00.000Z"
      },
      {
        "datprog": "2022-02-21T06:00:00.000Z"
      }
    ],
}

>Solution :

data is an object, but map() works with arrays. My guess is that you want to iterate through the rows:

data.floodguard_dates.rows.map(...)

For example. to get the dates you would do:

const dates = data.floodguard_dates.rows.map(row => row.datprog)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading