I am trying to make a filter for this information, this is an array of objects from a API with the information of all the products in the database, in this example I only show one product, but the API request all products.
[
{
"Id": 11,
"Name": "Papas fritas",
"Description": "Papas",
"Availability": 1,
"Price": 1,
"Stock": 10,
"Promotion": 0,
"Discount": 0,
"Visible": 1,
"CreationDate": "2021-04-22T18:51:51.000Z",
"UpdateAt": null,
"Photo": [
{
"Id": 21,
"Photo": "photo.png"
}
],
"Rating": 4.5,
"Category": [
{
"Id": 2,
"Category": "Moda",
"Icon": "Fashion"
},
{
"Id": 3,
"Category": "Fitness",
"Icon": "Fitness"
}
],
"Subcategory": [],
"Characteristics": [],
}
Now I make a class that have the methods for short and filter this array, but I have a problem filtering the information, I don't know how to filter the information by category using something like this:
[{Category: 'Art,Fitnness'}]
It's also is possible that the Promotion property will be formatted this way:
[{Promotion: 'true'}]
As you can see this array with the filters can have more than one property and can be a different property than category i need to validate the values because all values in the array are strings and sometimes Array.filter doesn't work comparing a string "true" === 1
What I implement for this is this function, query is the array of the products and queryvalues is the filter array
FilterFuntion(Query, QueryValues)
{
QueryValues = Object.entries(QueryObj).map((e) => ( { [e[0]]: e[1] } ));
let FilteredArray = Query;
QueryValues.map((Filter) =>
{
var key = Object.keys(Filter)[0];
FilteredArray = ValidateFilter(key, Filter[key], FilteredArray);
});
return FilteredArray;
}
ValidateFilter(Key, Value, array)
{
return array.filter((El) =>
{
if (Value === "true" || Value === "false")
{
return Boolean(El[Key]) === Boolean(Value);
}
if(Array.isArray((El[Key]))
{
(El[Key]).filter((sub) =>
{
return String(sub[Key]) === String(Value);
});
}
return String(El[Key]) === String(Value);
});
}
So I validate if the value of the filter is a bool string or int first and next I return the value that match, that work correct whit all the normal values but when the value nested in another array doesn't work, it returns a filter array of category instead of return the entire product, I don't know how to make this work when there are nested arrays, and when I would want to filter on multiple categories, how can I do it ?.
[{Category: 'Art,Fitnness'}]
Another thing is for example when the filter has a value between two numbers, for example look Rating property, I need to filter and return only the products that have a rating between 5 and 4
[{Promotion: 'true'}, {Category: 'Fitness'}, {Rating: '5,4'}]