简体   繁体   中英

Filter array by finding multiple conditions in nested array of objects

I have an array with a nested array of objects, I want to filter the data where the object of the nested arrays meets multiple conditions.

Here's the sample data.

const providerList = [
  {
    id: "bac4ef8d",
    provider_name: 'Paa Ra'
    provider_gender: "Male",
    provider_item: [
      {
        itemID: "5911319b"
        is_approved: true,
        is_active: true,
      },
      {
        itemID: "937a56d7"
        is_approved: true,
        is_active: true,
      },
    ],
  },
  {
    id: "9df373d5",
    provider_name: "Che Ta",
    provider_gender: "Female",
    provider_item: [
      {
        itemID: "5911319b"
        is_approved: true,
        is_active: true,
      }
    ],
  }
]

These are the filters, note that the itemID can have any number of elements.

const itemFilter = {
  itemID: ["5911319b", "937a56d7"],
  is_approved: [true],
  is_active: [true],
};

Here's my code, however the output does not return as desired.

const filterProviders = providerList.filter(provider =>
  provider.provider_item.every(item =>
    Object.entries(itemFilter).every(([k, v]) => v.includes(item[k]))),
);

I require to filter the providerList and returning providers where the provier_item matches all values in itemFilter

Is this what you are after:

 const providerList = [{ id: "bac4ef8d", provider_name: 'Paa Ra', provider_gender: "Male", provider_item: [{ itemID: "5911319b", is_approved: true, is_active: true, }, { itemID: "937a56d7", is_approved: true, is_active: true, }, ], }, { id: "9df373d5", provider_name: "Che Ta", provider_gender: "Female", provider_item: [{ itemID: "5911319b", is_approved: true, is_active: true, }], } ] const itemFilter = { itemID: ["937a56d7"], is_approved: [true], is_active: [true], } const filterProviders = providerList.reduce((acc, provider) => { provider.provider_item = provider.provider_item.filter(item => ( itemFilter.itemID.includes(item.itemID) && itemFilter.is_approved.includes(item.is_approved) && itemFilter.is_active.includes(item.is_active) )) if (provider.provider_item.length > 0) { acc.push(provider) } return acc }, []) console.log(filterProviders)

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