Reputation: 81
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.
Upvotes: 0
Views: 155
Reputation: 81
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.
Upvotes: 2