How do I display option inputs in HTML from API

I’m trying to fetch data from my API, and put it in ‘option’ input.
But all I’m geting is [object Object]. And I would like to get days of the week.

const daysOptions = document.querySelector("#days");

const getData = async (url) => {
  try {
    const res = await fetch(url);
    const data = await res.json();

    if (data.length > 0) {
      return data;
    }
  } catch (err) {
    alert(err);
  }
};

const createOptions = async () => {
  const dataDays = await getData("http://localhost:8080/v1/days/getdays");
  console.log(dataDays);

  dataDays.forEach((day) => {
    const selectOption = document.createElement("option");
    selectOption.value = day;
    // selectOption.id = id;
    selectOption.textContent = day;
    daysOptions.append(selectOption);
  });
};

createOptions();

What I’m fetching is:

0: {id: 1, day: 'Monday'}
1: {id: 2, day: 'Tuesday'}
2: {id: 3, day: 'Wednesday'}
3: {id: 4, day: 'Thursday'}
4: {id: 5, day: 'Friday'}

>Solution :

After fetching when you are looping you should code like this below

dataDays.forEach((item) => {
  const selectOption = document.createElement("option");
  selectOption.value = item.day;
  // selectOption.id = id;
  selectOption.textContent = item.day;
  daysOptions.append(selectOption);
});

Here using the item I am accessing each object from the fetched list, and item.day is getting the value of the day.

if this solve your issue, let me know by replying or upvoting. Thanks

Leave a Reply