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
You can use reduce to achieve that result
const 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"
}
]
const productMenu = products.reduce((menu, item) => {
const existingCategory = menu[item.productCategory] || []
return {
...menu,
[item.productCategory] : [...existingCategory, item]
};
}, {})
console.log(productMenu)
you can do this:
function convert(products) {
const result = {}
products.forEach(p => {
const cat = p.productCategory
if (Array.isArray(result[cat]))
result[cat].push(p.productName)
else
result[cat] = [p.productName]
})
return result
}
const convertedProducts = convert(products)
the result should be like this:
{
'cat 1': [ 'product A' ],
'cat 2': [ 'product B' ],
'cat 3': [ 'product C', 'product D' ]
}
you can iterate the result object like this:
for(let key in result){
// do something with result[key]
}
You can store the result in an object where key would represent the Category and the value would be an array of products.
const categories = products.reduce((acc, curr) => {
acc[curr.productCategory]
? acc[curr.productCategory].push(curr.productName)
: (acc[curr.productCategory] = [curr.productName]);
return acc;
}, {});
This would output:
{
cat 1: ['product A']
cat 2: ['product B']
cat 3: ['product C', 'product D']
}