Max Tommy Mitschke Max Tommy Mitschke - 4 months ago 9
Javascript Question

.map() undefined even though I pass an array

I'm trying to map an array in my Component render method but it keeps saying .map is not a function even though it's an array.

return (
<select className="c-select">
<option value="">Choose your city</option>
{console.log(state.cities.items)}
{state.cities.items.map(city => <option key={city.slug} value={city.slug}>{city.name}</option>)}
</select>
);


The console log gives me this result:
[{"id":1,"name":"Berlin","country":"Germany","default":1,"slug":"berlin"},{"id":2,"name":"Hamburg","country":"Germany","default":0,"slug":"hamburg"}]


I have no clue why .map is undefined - Am I missing something here?

Thanks!

Answer

If you're using Chrome or Firefox, it looks like state.cities.items is a JSON string, not an Array.

Try

{JSON.parse(state.cities.items).map(...)}

When you console.log real Arrays, the output will look like Array [ Object, Object ] in Firefox or >[Object] in Chrome