I want to filter my product data with multiple as well as Dynamic filter conditions. First my raw data format is:
[{
...,
"_source": {
...,
"categories": [
"home",
"office"
],
...,
"attributes": {
"colors": [
"Red-White-Blue",
"Orange-Red-Black"
]
},
...,
}
}]
Now, I have another dynamic object whose key-value pair is generated at run time. The object is:
{
selectedFilters: {
categories: ["home", "office", "public"],
colors: ["Red-White-Blue", "Orange-Red-Black", "Blue"],
...
}
}
Here, maybe categories array be there, or maybe not. Like wise, the keyvalue pair is generated dynamically.
Now, I want to loop through all the keys from selectedFilters
object and find them in their respective array from my raw data.
Let say if selectedFilters contains categories
as home
and colors
contain white
, then all the product with home category
and white colors
should be returned from main product data. If there is no value in colors
, then it should return all product data with category
as home, likewise if color
is white and categories
is empty, then it should return all white color products no matter what category.
How can I achieve this with or without Lodash?
This below code worked for dynamic keys in searchFilters. And then, I'm filtering data from the product data.
let keys = Object.keys(this.selectedFilters);
keys.forEach(function(filterKey) {
let filterdProducts = _.filter(self.products, function(o) {
let flg = false;
let searchFilterKey = self.selectedFilters[filterKey];
searchFilterKey.forEach(function(sKey) {
let ind = o._source[filterKey].indexOf(sKey)
if (ind > 0)
flg = true;
})
if (flg)
return o;
});
self.filteredProducts = filterdProducts
});