As you see in the data below, we have a list of restaurants, each restaurant has a list of different menus, and each menu has a list of products
my question is: how can I filter a restaurant based on the product object ? so as you see the second product object (Typical salad) is missing the price so I want to remove the whole restaurant (Resturant 1) object from data, how can I do it?
const data = [
{
name: "Resturant 1",
phone: "0000555823",
multiple_menus: [
{
name: "salads",
products: [
{
name: "French salad",
price: 15.5
},
{
name: "Typical salad",
}
]
},
{
name: "burgers",
products: [
{
name: "cheese burger",
price: 15.5
},
{
name: "American burger",
price: 10
}
]
},
]
},
{
name: "Resturant 2",
phone: "0000555823",
multiple_menus: [
{
name: "salads",
products: [
{
name: "French salad",
price: 15.5
},
{
name: "Typical salad",
price: 5.5
}
]
}
]
},
]
CodePudding user response:
As a more readable answer, this is a solution
const filteredData = data.filter((restaurant)=>{
const everyMenuProductHasPrice = restaurant.multiple_menus.every((menu)=>{
const everyProductHasPrice = menu.products.every((product)=>!!product.price)
return everyProductHasPrice
})
return everyMenuProductHasPrice
})
CodePudding user response:
Basically a combination of array filter
and array some
.
Bring me all restaurants that don't have some menu who has a product without a price.
const data = [{name:"Resturant 1",phone:"0000555823",multiple_menus:[{name:"salads",products:[{name:"French salad",price:15.5},{name:"Typical salad"}]},{name:"burgers",products:[{name:"cheese burger",price:15.5},{name:"American burger",price:10}]},]},{name:"Resturant 2",phone:"0000555823",multiple_menus:[{name:"salads",products:[{name:"French salad",price:15.5},{name:"Typical salad",price:5.5}]}]},];
var result = data.filter(function(restaurant) {
return !restaurant.multiple_menus.some(function(menu) {
return menu.products.some(function(product) {
return !product.price
})
})
});
console.log(result)
.as-console-wrapper {max-height: 100% !important}