Home > Back-end >  How to access datavalues using Map Function?
How to access datavalues using Map Function?

Time:07-16

I have a "data" state which stores the values taken from my database.

const [data, setData] = useState([]);

"data" contains an array of objects which was extracted from my database.

// so data is essentially (if I console.log it): 
data = [
{student:"Jeff",country:"London"}, 
{student:"Benjamin",country:"France"},
{student:"Franklin",country:"USA"}
];

I am using React Select to display the labels of this data (I only want "student" data) but I am not sure how to map this data into values and labels to put them as options in my React Select component. I have tried the following but it gives me an error.

import Select from "react-select";
function myTable() {
   const myOptions = data.map(info => {
       value: {info.student},
       label: {info.student}
   });

   return (
     <tr>
        <td>
            <Select isMulti options={myOptions}></Select>
        </td>
     </tr>
   )
};

I want my options to contain values and labels from my data state object.

CodePudding user response:

You don't need to add the info.student in an object.

import Select from "react-select";
function myTable() {
   const myOptions = data.map(info => ({
       value: info.student,
       label: info.student
   }));

   return (
     <tr>
        <td>
            <Select isMulti options={myOptions}></Select>
        </td>
     </tr>
   )

Codesandbox example

CodePudding user response:

You have syntax error with your Array.prototype.map function. It should be:

const myOptions = data.map(info => ({
  value: info.student,
  label: info.student
}));

// or
const myOptions = data.map(info => {
  return {
    value: info.student,
    label: info.student
  }
});
  • Related