1

I'm trying to read the data of the JSON in Next.JS and can't get past the nested array. I can get the first .map logic to work. I want to print out the data in the below section of the JSON.

I can get Home, One and Two printed out. Just need to print Three and Four that is in the below array. I thought using "menuItem.below.map(childItem => (" would work.

TypeError: Cannot read properties of undefined (reading 'map')
{menuItem.below.map(childItem => (

Here is the Json.

[
{
"key": "standard.front_page",
"title": "Home",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "700d2d65-0307-471a-b843-c09ffcae0d9b",
"title": "One",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "51270262-f99d-4557-ad55-8bd8727ab15f",
"title": "Two",
"absolute": "http://localhost:8888/",
"relative": "/",
"below": [
{
"key": "f23a85d8-f430-47c8-87a1-c965d4078d0c",
"title": "Three",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "89b2d6b2-81d0-4d85-a0eb-8ce4e3dac80e",
"title": "Four",
"absolute": "http://localhost:8888/",
"relative": "/"
}
]
}
]
function MainMenu({ menuLists }) {
  return (
   <div>
      {menuLists.map(menuItem => (
        <div>
          <Link href={menuItem.absolute}><a>{menuItem.title}</a></Link>

          {menuItem.below.map(childItem => (
            <div>{childItem.title}</div>
          ))}
        </div>

      ))}
  </div>
  )
}

export async function getStaticProps() {

  const response = await fetch('http://localhost:8888/api/menu_items/main', config);
  const menuLists = await response.json();
  
  return {
    props: {
      menuLists: menuLists,
    },
  }
}

export default MainMenu

1 Answer 1

1

The below property is not always present in the menuItems, so you must first make sure it exists:

{menuItem.below && menuItem.below.map(childItem => (
   <div>{childItem.title}</div>
))}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfect; thanks for the help. With all the google searching I did; nobody had that in their code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.