简体   繁体   中英

How to map through nested array of objects in React

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.

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 .

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"))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM