简体   繁体   中英

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

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

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}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM