繁星点点滴滴
只需使用Array.map和Array.filter:let products = [{ "id":"1", "Name":"Coke 500ml", "Price":"80", "Quantity": "50", "Category":"Beverages"},{ "id":"2", "Name":"Cake", "Price":"150", "Quantity": "40", "Category":"Appetizer"},{ "id":"3", "Name":"Beef Ribs", "Price":"100", "Quantity": "50", "Category":"Side Items"},{ "id":"4", "Name":"Cabbage Salad", "Price":"50", "Quantity": "30", "Category":"Salads"},{ "id":"5", "Name":"Cake", "Price":"150", "Quantity": "30", "Category":"Appetizer"},{ "id":"6", "Name":"Beef Ribs", "Price":"100", "Quantity": "30", "Category":"Side Items"}];let categories = [{ "id" : "1", "name" : "Appetizers", "Status" : "Active" },{ "id" : "2", "name" : "Salads", "Status" : "Active" },{ "id" : "3", "name" : "Entrees", "Status" : "Active" },{ "id" : "4", "name" : "Side Items", "Status" : "Active" },{ "id" : "5", "name" : "Beverages", "Status" : "Active" }];let result = categories.map(c=>{ return { ...c, products : products.filter(p=>p.Category===c.name) }})console.log(JSON.stringify(result,null,2));
慕莱坞森
您应该尝试使用Array.filter()方法:const arr = [ { "id": "1", "Name": "Coke 500ml", "Price": "80", "Quantity": "50", "Category": "Beverages" }, { "id": "2", "Name": "Cake", "Price": "150", "Quantity": "40", "Category": "Appetizer" }, { "id": "3", "Name": "Beef Ribs", "Price": "100", "Quantity": "50", "Category": "Side Items" }, { "id": "4", "Name": "Cabbage Salad", "Price": "50", "Quantity": "30", "Category": "Salads" }, { "id": "5", "Name": "Cake", "Price": "150", "Quantity": "30", "Category": "Appetizer" }, { "id": "6", "Name": "Beef Ribs", "Price": "100", "Quantity": "30", "Category": "Side Items" }];function filterArrayByCategory(category) { return arr.filter(el => el.Category === category);}console.log(filterArrayByCategory('Appetizer'));