0

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 ?

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"
      }
    ],
}
4
  • 1
    Please edit your question, showing the results of running console.log(JSON.stringify(data, null, 2)) at the start of listDataDates. data is likely not an array. Commented Jan 20, 2023 at 17:11
  • Use data.floodguard.rows Commented Jan 20, 2023 at 17:13
  • ok, but I still receive TypeError: data.map is not a function how can I structure the function ? Commented Jan 20, 2023 at 17:16
  • @BenJohnson I think you have to use data['floodguard_dates'].rows instead of directly passing the data object Commented Jan 20, 2023 at 17:31

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.