我有一个购物清单应用,我想根据类别显示产品,我希望产品在类别名称看起来不同的情况下显示类似这样的内容
这是我的产品代码
var products = [{
"id": "219",
"product_id": "198909",
"sku": "20148089",
"prod_name": "Chocolate Mousse 1L",
"vendor": "Woolworths",
"price": "45.09",
"status": "0",
"category": "Bakery & Desserts"
}, {
"id": "220",
"product_id": "199403",
"sku": "20008307",
"prod_name": "Medium Carrots 500g",
"vendor": "Woolworths",
"price": "10.99",
"status": "0",
"category": "Carrots & Beetroot"
}, {
"id": "221",
"product_id": "204759",
"sku": "6009207908908",
"prod_name": "Fresh Spicy Lentil & Vegetable Soup 600g",
"vendor": "Woolworths",
"price": "40.78",
"status": "0",
"category": "Fresh Food"
}, {
"id": "222",
"product_id": "199015",
"sku": "6009182131643",
"prod_name": "Bulk White Gouda Cheese 900g",
"vendor": "Woolworths",
"price": "126.45",
"status": "0",
"category": "Cheese"
}];
let categories = {};
products.forEach(product => {
if (!Object.keys(categories).includes(product.category)) {
categories[product.category] = {
items: []
};
}
});
products.forEach(product => {
Object.keys(categories).forEach(category => {
if (product.category === category) {
categories[category].items.push(product);
}
});
});
console.log(categories);
答案 0 :(得分:0)
var categories=products.map(product=>product.category)
var result=categories.map(category=>{
return{'category':category,'products':products.filter(product=>product.category==category)}
})