{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.
Use a map() inside a map() function in React # To use a map() inside a map() function in React: Call map() on the outer array, passing it a function. On each iteration, call the map() method on the other array.
In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.
You can do a map within a map as follows:
e.g. 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With