Lets assume I have an array of objects:
let users = [{
name: "Mark",
location: "US",
job: "engineer"
},
{
name: "Mark",
location: "US",
job: "clerk"
},
{
name: "Angela",
location: "Europe",
job: "pilot"
},
{
name: "Matthew",
location: "US",
job: "engineer"
}]
and I have a filter object with all categories I want to filter data against (there can be multiple values per key):
const filters = {
name: ["Mark", "Matthew"],
location: ["US"],
job: ["Engineer"]
}
Based on these filters and data the expected result would return:
[{name: "Mark", location: "US", job: "Engineer"}, {name: "Matthew", location: "US", job: "Engineer"}]
I have tried filtering with:
users.filter(user => {
for(let k in filters) {
if(user[k] === filters[k]) {
return true;
}
}
})
however, this method doesn't take into account that a filter category might contain more than one value which I can handle by doing like:
filters[k][0] or filters[k][1]
but it isn't dynamic.
If anyone has any input that would be much appreciated! Thank you.