0

I have a mega menu design with the following data structure

const megaMenuLink = [
   {
     name: 'E-services',
     link: '/e-services',
     hasSubmenu: true,
     subMenuItems: [
            {
                name: "Access E-services",
                link: "/access",
           },

             {
                name: "Register",
                link: "/register"
           }
       ]
    },

        {
        name: "Other services",
        link: "/services",
        hasSubmenu: false,
    }
]

I have accessed the name property with {#each} block

{#each megaMenuLink as link}
    <li>{link.name}</li>
{/each}

How do I loop through the inner subMenuItems based on condition of 'hasSubmenu' is true?

2 Answers 2

2

You could either add an #if block with another #each block inside

<ul>
    {#each megaMenuLink as link}
    <li>{link.name}</li>
        {#if link.hasSubmenu}
        <ul>
            {#each link.subMenuItems as link}
            <li>{link.name}</li>
            {/each}
        </ul>
        {/if}
    {/each}
</ul>

or make use of <svelte:self> (docs / tutorial) when creating a component

<LinkList items={megaMenuLink} />
<script>
    export let items
</script>

<ul>
    {#each items as link}
    <li>{link.name}</li>
      {#if link.hasSubmenu}
      <svelte:self items={link.subMenuItems} />
      {/if}
    {/each}
</ul>

REPL

Sign up to request clarification or add additional context in comments.

Comments

0
let name ;
  let link ;
  this.megaMenuLink.forEach((obj)=> {
    if(obj.hasSubmenu === true && obj.subMenuItems){
       name = obj.subMenuItems.map(e=>e.name)
       link = obj.subMenuItems.map(e=>e.link);
    }
  } );
  console.log(name, "and",  link);
   
}

// these code works for javascript

Comments

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.