I am creating a menu application using React. My app accepts an array of objects which then need to be mapped into a menu. The structure of the menu is like this:
Title
Header
Item
Item
Header
Item
Item
The data objects I receive are structured like: {title: "Drinks", header: "Beer", item: "Blue Moon"}. I filter the array so I only get objects with the same title. My issue is that I do not know how many different headers are going to come in. I need my mapping function to display each header and all associated items. Currently the title is handled outside of the mapping function because there will only be one title per menu.
<div className={style.menuItemTitle}>{title}</div>
{currentMenu.map((item, index) => (
<div className={style.menuHeader}>{item.header}</div>
<div className={style.menuItem}>{item.item}</div>
))}
The above code lists the header above every single item. I only want each header to display once with all of the associated items below.
currentMenu.filter(item=>item.header==='beer').map(element=>element.item)gives list of items{ title: "Drinks", items: [ { header: "Beer", items: [ { name: "Blue Moon" }, { name: "Heineken" } ] }, { header: "Liquor", items: [ { name: "Jameson Irish Whiskey" }, { name: "Stolichnaya Vodka" } ] }Then it would be easier to map them.const uniqueHeaders=(menu)=>{ let result=[]; for (let item of menu){ if (result.indexOf(item.header)===-1){ result.push(item.header)}; }; return result}it returns array of unique headers