Using a map on a map in jsx
{normalizedData.map(obj =>
<div key={obj.display_date_numberic}>
<div>{obj.display_date_numberic}</div>
</div>
{!isEmpty(obj.applicants) && obj.map(obj2 =>
<div className="events">{obj2.person.name}</div>
)}
)}
I am getting an error on the following line:
{!isEmpty(obj.applicants) && obj.map(obj2 =>
Why can't I use the map function inside another map? normalizedData
has an array of objects and each obj
has a different array of objects.
source to share
The obvious mistake you are using in your code is that you have to map to obj.applicants
in the inner map and not obj
and return one element from the outer map
Also if obj.applicants is an array, don't need to use isEmpty
{normalizedData.map(obj =>
<div>
<div key={obj.display_date_numberic}>
<div>{obj.display_date_numberic}</div>
</div>
{ obj.applicants.map(obj2 =>
<div className="events">{obj2.person.name}</div>
)}
</div>
)}
source to share
The reason is that you are trying render
more than one item and we cannot do that, we can only return one item. So, wrap all your logic and elements inside one div
like this:
{normalizedData.map(obj =>
<div key={obj.display_date_numberic}>
<div>{obj.display_date_numberic}</div>
{Array.isArray(obj.applicants) && obj.applicants.map(obj2 =>
<div className="events">{obj2.person.name}</div>
)}
</div>
)}
Assuming it obj.applicants
is array
, use Array.isArray to check if any value is a valid array or not
Note: We can map
only use on array
not on any object
, so if obj is an object and uses Object.keys(obj)
to get array
all then use map
.
source to share
You can make a map on a map like this:
eg data
outerArray: [
{ id: '1st', innerArray: [ 'this', 'that' ]},
{ id: '2nd', innerArray: [ 'some', 'what' ]},
]
You can use JSX:
<ul>
{outerArray.map(outerElement => {
return outerElement.innerArray.map(innerElement => (
<li>{innerElement} - {outerElement.id}</li>
))
})}
</ul>
or
<ul>
{outerArray.map(outerElement => (
outerElement.innerArray.map(innerElement => (
<li>{innerElement} - {outerElement.id}</li>
))
))}
</ul>
which renders:
<ul>
<li>this - 1st</li>
<li>that - 1st</li>
<li>some - 2nd</li>
<li>what - 2nd</li>
</ul>
source to share