Building an E-Commerce Store - Browsing Products Chapter 10
}
if(Object.keys(filters).length) {
category.productDetails = category.productDetails.filter(
p => this.filtering(p, filters)
);
}
if(!category) {
this.categoryNotFound = true;
}
return category;
}
}
Refresh your app to ensure the products still show.
To filter products, there is quite a complex process involved. We want to check whether an
attribute is in the query parameters; if it is, we set a placeholder value of false. If the
attribute on the product matches that of the query parameter, we set the placeholder to
true. We then repeat this for each of the query parameters. Once complete, we then only
show products that have all of the criteria.
The way we are going to construct this allows products to be OR within the categories, but
AND with different sections. For example, if the user were to pick many colors (red and
green) and one tag (accessories), it will show all products that are red or green accessories.
Our filtering is created with the tags, vendor, and then dynamic filters. As two of the
properties are fixed, we will have to check these first. The dynamic filters will be verified by
reconstructing the way they were built.
Create a hasProperty object, which will be our placeholder object for keeping track of the
query parameters the product has. We'll begin with the vendor – as this is the simplest
property.
We start by looping through the query attributes – in case there is more than one (for
example, red and green). Next, we need to confirm that the vendor exists in the query – if
it does, we then set a vendor attribute in the hasProperty object to false. We then check
whether the vendor handle is the same as the query attribute. If this matches, we change
our hasProperty.vendor property to true:
filtering(product, query) {
let display = false,
hasProperty = {};
Object.keys(query).forEach(key => {