how can I filter a parent object based on the inner (child) object?

Viewed 25

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
          }
        ]
      }
    ]
  },
]
1 Answers

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
})
Related