Home > Software design >  How can I access array items inside an object
How can I access array items inside an object

Time:10-08

I have an array which contains multiple objects (which have their own array of objects inside them). What I'm trying to do is map through each object's "subMenuItems" array and output the values inside.

Here's my Array:

export const MenuItems = [
  {
    category: 'Buy',
    subMenuItems: [
      {
        title: `Watching`,
        link: '/watching',
      },
      {
        title: `Bids & Offers`,
        link: '/bids-offers',
      },
      {
        title: `Bought`,
        link: '/bought',
      },
    ],
  },

  {
    category: 'Sell',
    subMenuItems: [
      {
        title: `Selling`,
        link: '/selling',
      },
      {
        title: `Sold`,
        link: '/sold',
      },
      {
        title: `Sell with us`,
        link: '/sell-with-us',
      },
    ],
  },
];

I'm able to get each object's category no problem by doing this:

  const listItems = MenuItems.map((item, i) => (
    <li key={i}>{item.category}</li>
  ));


Render:
return(
<ul>{listItems}</ul>
)

However I can't seem to get the syntax right when trying to access the "subMenuItems" in each object.

My end goal is to have a function that returns each category with it's sub menu items below it: E.G.

Buy

 - Watching
 - Bids & offers
 - Bought

Sell

 - Selling
 - Sold
 - Sell With Us

Hope that makes sense :) Thanks!

CodePudding user response:

You can do the same thing and render them using .map:

  const listItems = MenuItems.map((item, i) => (
    <li key={i}>
     {item.category}
     <ul>
       {item.subMenuItems?.map((index, subMenu) => (
         <li key={subMenu.title}> // index as key can be problematic 
            <a href={subMenu.link}>{subMenu.title}</a>
         </li>
       )}
     </ul>
    </li>
  ));

CodePudding user response:

You could map the subMenuItems into a ul and add it to your outer li

const listItems = MenuItems.map((item, i) => (
    const itemlist = item.subMenuItems.map((a, b) => (
        <li key={a.title}><a href={a.link}>{a.title}</a></li>
    ));
    <li key={i}>{item.category}<ul>{itemlist}</ul></li>
));
  • Related