Building an E-Commerce Store - Browsing Products Chapter 10
categories[type.handle].products.push(product.handle);
});
Viewing the app now will reveal all the categories in the JavaScript console – allowing you
to see the magnitude of how many categories there are.
Let's combine any categories with two or fewer products into the "other" category – not
forgetting to remove the category afterward. After the product loop, loop through the
categories, checking the count of the products available. If fewer than three, add them to
the "other" category:
Object.keys(categories).forEach(key => {
let category = categories[key];
if(category.products.length < 3) {
categories.other.products =
categories.other.products.concat(category.products);
}
});
We can then delete the category we've just stolen the products from:
Object.keys(categories).forEach(key => {
let category = categories[key];
if(category.products.length < 3) {
categories.other.products =
categories.other.products.concat(category.products);
delete categories[key];
}
});
And with that, we have a much more manageable list of categories. One more
improvement we can make is to ensure the categories are in alphabetical order. This helps
users find their desired category much quicker. In JavaScript, arrays can be sorted a lot
more easily than objects, so once again, we need to loop through an array of the object keys
and sort them. Create a new object and add the categories as they are sorted to it.
Afterward, store this on the state object so we have the categories available to us:
categories(state, payload) {
let categories = {},
other = {
title: 'Miscellaneous',
handle: 'other'
};
Object.keys(payload).forEach(key => {