Reputation: 101
How do i dynamically display an array that has multiple arrays. The nested arrays have multiple objects.
e.g.
Var obj =
[
[
{
name: "Test 1",
category: "Test 1"
},
{
name: "Test 2",
category: "Test 1"
},
],
[
{
name: "Test 1",
category: "Test 2"
},
{
name: "Test 2",
category: "Test 2"
},
]
]
So how do i dynamically display this and render it in a react component I tried [below] and it works perfect and displays the first array-object, but i cant figure out a way to make it display the rest
list = obj[0].map((e, index) => {
return (
<div key={index}>
<p>{e.name}</p>
<h6>{e.category}</h6>
</div>
)
})
return (
<div>
{list}
</div>
)
Upvotes: 0
Views: 109
Reputation: 27579
You have a couple of options here.
One is to explicitly loop over the outer array and then the inner arrays:
const list = obj.map(cat => cat.map((e, index) => {
return (
<div key={index}>
<p>{e.name}</p>
<h6>{e.category}</h6>
</div>
)
}));
The problem here is that index
will not be unique on the page. As a general rule, you should not be using an array index as a component key anyway. You'd be better off using something like
(
<div key={`${e.name}-${e.category}`}>
<p>{e.name}</p>
<h6>{e.category}</h6>
</div>
)
Another approach would be to flatten the array:
const list = [].concat(...obj).map(e => (
<div key={`${e.name}-${e.category}`}>
<p>{e.name}</p>
<h6>{e.category}</h6>
</div>
);
Upvotes: 1