Reputation: 133
I'm trying to map through an array, and for each key, map through the nested array of objects to print out grouped values.
I keep getting .map() is not a function for my nested arrays.
I have tried Object.Keys for the objects and map() for the arrays but I can't seem to get anything to print correctly.
Grouped Array
{Airport: Array(1), Motorway: Array(2), Other: Array(2), Train: Array(2), Subway: Array(1)}
Nested Arrays
Airport: Array(1)
0: {Station: "Airport", Description: "This is a description for the Airport", …}
Motorway: (2) [{…}, {…}]
Trying to print the mapped results:
return (
<Wrapper>
{Object.keys(list).map((key) => {
key.map((station) => {
console.log(station);
})
})}
</Wrapper>
)
I thought as the parent was an object, and the children are arrays, that Object Keys then the map function would work, but it throws the .map() is not a function error. Any help would be greatly appreciated.
Upvotes: 2
Views: 2995
Reputation: 51
the great option from me, you define that object not on jsx, like this
const objMap = Object.keys(list).map((key) => {
return list[key].map((station) => {
station : station[key].station
description : station[key].description
})
});
and then on jsx you can call
{objMap.map(e => console.log(e.get("station"))}
Upvotes: 1
Reputation: 31703
The reason why this doesn't work is because you are trying to do .map
in the key
. key
is just an string.
You should do the mapping over list[key]
wich is the array
{Object.keys(list).map((key) => {
return list[key].map((station) => {
console.log(station);
// you should return something here
})
})}
Another thing you can do is loop through the values.
{Object.values(list).map((value) => {
return value.map((station) => {
console.log(station);
// you should return something here
})
})}
This way, values
is the array you want and you can use .map
.
Upvotes: 4