On a JSX file, I need to loop through two levels of an Object to render the information each inner Array stores. It looks something like: Object > Object > Array
My data is structured this way:
const data = {
group1: {
subgroup1: [{...}, {...},{...}],
...
},
...
}
So I'm trying to acomplish something like this:
return (
<ul>
for (group in data) {
<li>Group Name
<ul>
for(subgroup in group) {
<li>Subgroup Name
<ul>
subgroup.map()
</ul>
</li>
}
</ul>
</li>
}
</ul>
)
I know for loops are not allowed inside a JSX file but converting my object into multiple Arrays doesn't seem right either since I have no idea how many items might be coming form my API.
I solved this using Herohtar suggestion, extracting the key/value of each of the parent Objects in an Array format:
{
Object.entries(data).map(group => (
<ul key={group[0]}>
<li>{group[0]}
<ul>
{
Object.entries(group[1]).map(subgroup => (
<ul key={subgroup[0]}>
<li>{subgroup[0]}
<ul>
{
subgroup[1].map(item => (
<li key={item.code}>{item.name}</li>
)
)
}
</ul>
</li>
</ul>
)
)
}
</ul>
</li>
</ul>
)
)
}
I wish there was a more elegant way of doing this though.
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.