{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'm 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 another array of objects.
You can do a map within a map as follows:
eg given data of
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 key={outerElement.id}>
{innerElement} - {outerElement.id}
</li>
))
})}
</ul>
or slightly more succinctly:
<ul>
{outerArray.map(outerElement => (
outerElement.innerArray.map(innerElement => (
<li key={outerElement.id}>
{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>
note the use of key= inside the map to ensure React has a unique reference for the element from each loop iteration. If you don't it will warn you!
Reason is, you are trying to render
more than one element, and we can't do that, we can return only one element. So wrap all the 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 obj.applicants
is an array
, use Array.isArray to check whether any value is a proper array or not
Note: We can use map
only on array
not on any object
, so if obj is an object and use Object.keys(obj)
to get an array
of all the keys then use map
on that.
The evident error that you hace in your code is that , you should be mapping on obj.applicants
in the inner map and not obj
and return a single element from the outer map
Also if obj.applicants is an array, no 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>
)}
只是建议,您可以使用for
而不是map
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.