'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 1:[1]

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

Solution 2:[2]

If you are using react js then you can use this code.

const Days = () => {
  const days = [
    { id: 1, day: "Monday" },
    { id: 2, day: "Tuesday" },
    { id: 3, day: "Wednesday" },
    { id: 4, day: "Thursday" },
    { id: 5, day: "Friday" },
    { id: 5, day: "Saturday" },
    { id: 5, day: "Sunday" },
  ];
  return (
    <div>
      <select name="days" id="">
        {days.map((day) => (
          <option key={day.id} value={day.day}>
            {day.day}
          </option>
        ))}
      </select>
    </div>
  );
};

ReactDOM.render(
  <div>
    DEMO
    <Days />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="rd" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Razu Ahmed Joy
Solution 2 jsN00b