Home > Software engineering >  How can I access object Id from selected option in select?
How can I access object Id from selected option in select?

Time:01-05

I have an object and the object.name is the select options. I need to get the object.id of the selected option in the select. Is it possible?

This is javascript, but if have some way to do that in typescript with Enum or another thing, works too!

I have this object:

const Months = {
  January: { id: 1, name: "January" },
  February: { id: 2, name: "February" },
  March: { id: 3, name: "March" },
  April: { id: 4, name: "April" },
  May: { id: 5, name: "May" },
  June: { id: 6, name: "June" },
  July: { id: 7, name: "July" },
  August: { id: 8, name: "August" },
  September: { id: 9, name: "September" },
  October: { id: 10, name: "October" },
  November: { id: 11, name: "November" },
  December: { id: 12, name: "December" },
};

and this App() fnc:

export default function App() {
  const [month, setMonth] = useState(Months.January.name);
  const [monthId, setMonthId] = useState(Months.January.id); // I tried this, but I don't know if it's possible

  const handleChange = (e) => {
    setMonth(e.target.value);
    // I tried to find something that return the Id for me in the 'e' but not success
  };

  return (
    <>
     <p>{month}</p>
     <p>{monthId}</p> // The id 1 is showed when I init the app, when I selected other option, it change to empty

     <select
      className={styles.selectMonth}
      defaultValue={month}
      onChange={handleChange}
     >
      {Object.keys(Months).map((key) => (
        <option key={key} value={key}>
          {Months[key].name}
        </option>
       ))}
     </select>
    <>
 );
}

CodePudding user response:

You have access to the month object using Months[e.target.value]

CodePudding user response:

You're not going to have your id in the select because you're not passing the id to the actual option. Based off what you have now, a simple solution is as follows:

const handleChange = (e) => {
   const m = e.target.value
    
   setMonth(m);
   setMonthId(Months[m].id)
};
  • Related