I am listning to user inputs for a filter value and storing them in to an array.
filters = []
my json data is to be filtered based on the values of the filters array.*But the filters can sometimes be empty if users haven't piked certain filters.
filters = ["9999", "91", "2", "5920"]
array = [
{carID: 38871, carNumber: 5918, dispatchStatus: 2, dataVersionNr: "AAAAAAhqD2Y=", postingID: 91,peratingCompanyID:2180
},{carID: 38872, carNumber: 5919, dispatchStatus: 2, dataVersionNr: "AAAAAAhqD2Y=", postingID: 81,peratingCompanyID:9999
},{carID: 38873, carNumber: 5920, dispatchStatus: 2, dataVersionNr: "AAAAAAhqD2Y=", postingID: 91,peratingCompanyID:9999
}]
I want to check if there are values in the filters and then apply all the filters to the json with this code that I got from the link below
var filtered = array.filter(o => {
if (filters[0] && o.peratingCompanyID== filters[0]) {
console.log(filters);
return true;
}
if (filters[1] && o.postingID == filters[1]) {
return false;
}
if (filters[2] && o.dispatchStatus== filters[2]) {
return false;
}
if (filters[3] && o.carNumber == filters[3]) {
return false;
}
return true;
});
I want to return the json who satisfies the above filter which is
[{carID: 38873, carNumber: 5920, dispatchStatus: 2, dataVersionNr: "AAAAAAhqD2Y=", postingID: 91,peratingCompanyID:9999}]
What am I missing here?
link: Search for multiple filters in JSON using Javascript forEach and indexOf