Skip to content
Advertisement

React map through json object

I am having trouble finding a way to iterate through this nested JSON data. I would like to display elements into select option list.

I store my data in a state after a request.

const [filterData, setFilterData] = useState([]);

useEffect(() => {
    ScenarioService.getFilterData().then((res) => {
      setFilterData(res.data);
      console.log(res.data);
    });
    setIsData(true);
  }, []);
{
"groups":[
      "group1",
      "group2"
   ],
"regions":[
      "region1",
      "region2"
]
}

I already tried:

<select>
      {Object.keys(filterData).map((key) => {
         return filterData[key].map((value) => {
           return <option>{key[value]}</option>;
         });
       })}
</select>
<select>
{Object.keys(filterData["regions"]).map((keyName, i) => {
   return (
     <option key={filterData[keyName]}>{filterData[keyName]}</option>
   );
})}
</select>
{filterData.regions.map((value)=>{
          return <option>{value}</option>
        })}

Last one gives my TypeError: Cannot read property ‘map’ of undefined.

If i try to set my state to setFilterData(res.data.regions) then i can call map() and it works, but then my state is only regions.

Result should look like: result

Advertisement

Answer

You could simplify the code duplication by using a function

const renderOpts = key => filterData[key].map(v => <option value={v}>{v}</option>)

Then to render the selects:

<select>{renderOpts('groups')}</select>

<select>{renderOpts('regions')}</select>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement