I have an array of objects and I’d like to filter it based on another array. If filters object value is only one, I can use only filter, but if there are one more values in filters object, nothing show. So use forEach inside the filter and wanted to return fit values. Could you please help me what the issue is? Thanks
Expected result:
[
{
"tags": [
"madewithout__gluten",
"madewithout__nuts",
],
"metafields": "Side"
}
]
const data = [
{
"tags": [
"madewithout__gluten",
"madewithout__nuts",
],
"metafields": "Side"
},
{
"tags": [
"madewithout__gluten",
],
"metafields": "Side"
},
{
"tags": [
"madewithout__nuts"
],
"metafields": "Side"
}
]
const filters = ['gluten', 'nuts']
const result = data.filter((v) => {
filters.forEach((tag) => {
if(!v.tags.includes(`madewithout__${tag}`))
return;
});
});
console.log(result);
>Solution :
Based on the semantics of the data you provided, you want to check if all filters are contained in tags:
const result = data.filter((v) =>
filters.every((tag) => v.tags.includes(`madewithout__${tag}`))
)
const data = [
{
"tags": [
"madewithout__gluten",
"madewithout__nuts",
],
"metafields": "Side"
},
{
"tags": [
"madewithout__gluten",
],
"metafields": "Side"
},
{
"tags": [
"madewithout__nuts"
],
"metafields": "Side"
}
]
const filters = ['gluten', 'nuts']
const result = data.filter((v) =>
filters.every((tag) => v.tags.includes(`madewithout__${tag}`))
)
console.log(result);