Building an E-Commerce Store - Browsing Products Chapter 10
Dynamically creating filters
With our fixed filters created and being watched, we can take the opportunity to create
dynamic filters. These filters will observe the variationTypes on the products (for
example, color, and size) and list out the options – again with the count of each one.
To achieve this, we need to first loop through the variationTypes on the products. Before
adding anything, we need to check to see if that variation type exists on the topics object,
if not – we need to add a skeleton object. This expands the variation (which contains the
title and handle) and also includes empty checked and value properties:
filters() {
if(this.categoriesExist) {
let category = this.categoryProducts(this.slug);
for(let product of category.productDetails) {
if(product.hasOwnProperty('vendor')) {
this.addTopic(this.topics.vendor, product.vendor);
}
if(product.hasOwnProperty('tags')) {
for(let tag of product.tags) {
this.addTopic(this.topics.tags, tag);
}
}
Object.keys(product.variationTypes).forEach(vkey => {
let variation = product.variationTypes[vkey];
if(!this.topics.hasOwnProperty(variation.handle)) {
this.topics[variation.handle] = {
...variation,
checked: [],
values: {}
}
}
});
}
}
return this.topics;
}