Reputation: 11
I'm trying to map through an array within an object in an array that I'm already mapping through. I'm a bit stumped and unsure of whether I can actually do this. How would I map through all roles and give them each their own div? Here's an example of what I've tried:
const Projects = [
{name: 'project one', roles: ['designer', 'developer']},
{name: 'project two', roles: ['designer', 'developer']}
]
{Projects.map((project, i) => (
<div>{project.name}</div>
{project.roles.map((role, i) => (
<div>{role}</div>
))};
))};
Thanks for your help!
Upvotes: 0
Views: 66
Reputation: 13807
You are on the right track, but you need to return a single JSX element from your transform function. To achieve this, you can wrap your elements in a dom element (like a div), but you can also use Fragment
or the <></>
shortcut (this allows you to wrap elements without producing unwanted DOM elements):
Projects.map((project) => (
<>
<div>{project.name}</div>
{project.roles.map((role) => (
<div>{role}</div>
))}
</>
))
In case you just want to iterate over the roles (I don't think this was your goal, but your question kinda sounds like that), you can use flatMap
first, where you can return an array in your transform function, and flatMap
will create a continuous array from those arrays:
const roles = Projects.flatMap((project) => project.roles)
roles.map((role) => <div>{role}</div>)
Also, don't forget to key
your mapped elements!
Upvotes: 1