Home > Net >  Render out nestled arrays in an object via map
Render out nestled arrays in an object via map

Time:12-23

I have data that looks like:

{
  title: "Category title",
  description: "Example description",
  lists: [
    {
      id: "popular",
      title: "Popular",
      items: [
        {
          id: 1,
          title: "title",
          provider: "provider",
          image: ""
        },
      ....
      ]
    },
    {
      id: "new",
      title: "New",
      items: [
        {
          id: 4,
          title: "title4",
          provider: "provider",
          image: ""
        },
       ....
      ]
    }
  ]
}

I want to render it out, and the object contains two nestled arrays - lists and items and for that I use map like this:

return (
    <>
      {iconItems?.lists.map((icon, i) => {
        return (
          <>
            <h3 key={i}>{icon.title}</h3>
            {icon.items.map((i) => {
              <h2 key={i.id}>{i.title}</h2>;
            })}
          </>
        );
      })}
    </>
  );

However, above will not work, and only title will be rendered out. What I am missing? Working sandbox: https://codesandbox.io/s/quirky-jerry-wfzso2?file=/src/App.js

I have tried to add id to the key props as, after Googling, could be an issue. But that didnt fix the problem.

CodePudding user response:

You need to return value from your function. Adding return like this will make it work:

return <h2 key={i.id}>{i.title}</h2>;
  • Related