I need to implement user filtering according to the rules that come with the JSON file along with the users. There are two types of rules: "exclude" and "include" . They can come either individually or two at once. Right now, my code works well when two rules come in at once. But when there is only one rule, then the error in the console is Cannot read properties of undefined (reading 'forEach'). How can this problem be solved?
Users and rules:
{
"data": [{
"user": "user1",
"city": "New York",
"disabled": false
},
{
"user": "user2",
"city": "London",
"disabled": false
},
{
"user": "user3",
"city": "Tokyo",
"disabled": true
}
],
"condition": {
"exclude": [{
"disabled": true
}],
"include": [{
"city": "New York",
}],
}
}
const data = responseJson.then((data) => {
var filteredUsers = advancedFilter(data.data, data.condition);
console.log(filteredUsers);
});
function advancedFilter(data, condition) {
return data.filter((dataItem) => {
var cond = true;
if ("exclude" in condition || "include" in condition) {
condition.exclude.forEach((condItem) => {
for (var key in condItem) {
cond = cond && dataItem[key] !== condItem[key];
}
});
condition.include.forEach((condItem) => {
for (var key in condItem) {
cond = cond && dataItem[key] === condItem[key];
}
});
}
return cond;
});
}