Home > Net >  Read a specific field from an array
Read a specific field from an array

Time:05-11

I have a select box that accepts multiple values. How can I read only the ID of the respective object from this array?

enter image description here

CodePudding user response:

You can do something like:

values.forEach(value=>{
 console.log(value.id); //here you can access id of each object.
})

CodePudding user response:

You can use the id of the objects as the value for the options and then you can extract the values wherever required like on form submission or selection change.

Refer to the snippet below:

const options = [
  { label: "Apple", id: 1 },
  { label: "Mango", id: 2 },
  { label: "Banana", id: 3 },
  { label: "Kiwi", id: 4 },
  { label: "Watermelon", id: 5 },
];

function App() {
  const [selectedOptions, setSelectedOptions] = React.useState([]);

  const handleChange = ({ target }) => {
    const currSelectedOptions = Array.from(target.selectedOptions).map(
      (opt) => opt.value
    );
    setSelectedOptions(currSelectedOptions);

    console.log("Selected Options", currSelectedOptions);
  };

  return (
    <select multiple value={selectedOptions} onChange={handleChange}>
      {options.map(({ label, id }) => (
        <option value={id} key={id}>
          {label}
        </option>
      ))}
    </select>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>

  • Related