Home > front end >  Map data in React to array of objects
Map data in React to array of objects

Time:03-23

When using react-select it demands an array of objects, not of data. https://github.com/JedWatson/react-select/issues/5032 "react-select does not actively support options that are just simple strings."

I have a list of cities, and I need to change that list to an object [{ label: "city", value: "city" }].

const [selectData, setSelectData] = useState([{ label: "city", value: "city" }]);

function This iterates over the data and should create an object array. But it doesn't....

const CreateSelectData = () => {
var getSelectDataList = [];
allCities.map(
  (city, index) =>
    (getSelectDataList = [...selectData,{label:city, value: city])
);
setSelectData(getSelectDataList);
};

output

 <Select
        options={selectData}
        className='optioncity'
        value='Select a city'
        onChange={handleCityChange}
      />

I have no idea what I have done wrong, but I have looked at it for hours :-) The Select never loads at all

CodePudding user response:

map is to transform from the original object into another object, but for your case, you should use forEach instead. And you should expand getSelectDataList which is your new array instead of selectData

const CreateSelectData = () => {
var getSelectDataList = [...selectData]; //initialise with your initial `selectData`
allCities.forEach((city, index) => {
   getSelectDataList = getSelectDataList.push({ id: index, name: city })
});
setSelectData(getSelectDataList);
};

If you want to use map. You can try this way

const CreateSelectData = () => {
   var getSelectDataList = allCities.map((city, index) => ({ id: index, name: city })); //create a new list with your expected value
   setSelectData([...selectData, ...getSelectDataList]);
};

CodePudding user response:

in your function change

allCities.map((city) =>
    (getSelectDataList = [...selectData, { label: city, value: city }])
);

to

allCities.map((city) =>
    (getSelectDataList = [...getSelectDataList, { label: city, value: city }])
);
  • Related