r/learnreactjs • u/eb2292 • Nov 02 '22
Iterating over nested array/dictionary
Hi guys, I am super new to react and JS. I am trying to iterate over a dictionary with nested children which is sent from my Flask backend to react. Why does this code work:
return (
<div>
{Object.keys(data).map((key, index) => (
Object.keys(data[key]).map((y, i) => (
<h2>
{key} : {y} : {data[key][y]}
</h2>
))
))}
</div>
);
But not this code?:
return (
<div>
{Object.keys(data).map((key, index) => (
<div>{key}</div>
Object.keys(data[key]).map((y, i) => (
<h2>
{key} : {y} : {data[key][y]}
</h2>
))
))}
</div>
);
I want to display each outer key once with the children array data underneath it
3
Upvotes
View all comments
Show parent comment
2
u/Mutiny42 Nov 02 '22
No problem, happy to help!
The code stopped processing after the first div because map can only return a single element per loop.
Because it came across a div, it assumes that the div (and whatever is inside of it) is the one thing you are asking to be returned.
Because you want multiple elements returned, we need to package it all up as a single element so that all of the code gets read and returned.
Does that make sense?