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?
CodePudding user response:
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>
CodePudding user response:
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