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
. The expected output for the above itemFilter
would be:
filterProviders = [
{
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,
},
],
}
]
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", "5911319b"],
is_approved: [true],
is_active: [true],
}
const filterProviders = providerList.reduce((acc, provider) => {
provider.provider_item = provider.provider_item.filter(item => (
itemFilter.itemID.every(ai => provider.provider_item.map(i => i.itemID).includes(ai)) &&
itemFilter.is_approved.includes(item.is_approved) &&
itemFilter.is_active.includes(item.is_active)
))
let providerCount = provider.provider_item.length
if (providerCount > 0 && providerCount === itemFilter.itemID.length) {
acc.push(provider)
}
return acc
}, [])
console.log(filterProviders)