From an API call I receive this JSON:
products: [
{
productName: "product A",
productCategory: "cat 1"
},
{
productName: "product B",
productCategory: "cat 2"
},
{
productName: "product C",
productCategory: "cat 3"
},
{
productName: "product D",
productCategory: "cat 3"
}
]
I want to use this to create a menu with dropdown. The mainmenu should contain the categories, the submenu should contain the products with the same category name. So, in this example, in the end there should be three menu items in the main menu, the third menu item contains a submenu with two products. I've tried many things but get kinda stuck. This is the only piece of code left, which obviously is not working.
const cat = [];
products.forEach(product => {
cat.push(product);
if (!cat.indexOf(product)) {
cat.push(product.productCategory);
console.log(product.productCategory);
}
EXPECTED RESULT:
CATEGORY A CATEGORY B CATEGORY C
Product 1 Product 2 Product 3
Product 4