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 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"
}
],
}
CodePudding user response:
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)