I’m trying to build a dynamic search function by using an eventListener and filtering the JSON results of an API call.
Everything works fine when I filter by name, but I’m really struggling to figure out how to filter through a dynamic array inside the object.
I’ve tried forEach, map and looked over other questions but can’t seem to find a solution…
let allContractors = []; // this is populated by an async function bellow, not included in code
searchBar.addEventListener("keyup", (e) => {
let target = e.target.value;
const filteredContractors = allContractors.filter((contractor) => {
return (
contractor.name.toLowerCase().includes(target.toLowerCase()) ||
contractor.categories[0].title.toLowerCase().includes(target.toLowerCase)
);
});
displayContractors(filteredContractors);
});
It works fine when I iterate a specific array index, but when I try to use forEach, includes cannot read the element.
contractor.categories.forEach(element => {
element.title
}).includes(target)
I’m sure there is a syntax error above, I’ve messed around with it quite a bit, just thought it would be helpful to show what I’m dealing with.