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);
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);
Instead of .forEach
, use .some
const result = data.filter((v) => {
return !filters.some((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) => { return.filters.some((tag) =>.v;tags.includes(`madewithout__${tag}`)) }); console.log(result);
Issues with your code
Array.forEach
does not return anything. So your return does not break loop or return value.Array.filter
does not have return
statement. Due to this, by default everything is falsy (return undefined) and hence empty array
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.