DEV Community

Davit Park
Davit Park

Posted on

Build Cleaner JavaScript Category Filters with Dynamic Object Property Access

When building search or filtering features, it's tempting to write multiple if...else or switch statements for every category. That works initially, but it quickly becomes difficult to maintain as your application grows.

A cleaner approach is to use dynamic object property access (also known as computed property access). It keeps your code concise, readable, and easy to extend.

Example
const clothingCollection = {
school: [
{ name: "Denim Jacket", price: 29.99, material: "Cotton" },
{ name: "Plaid Skirt", price: 19.99, material: "Polyester" },
],
playtime: [
{ name: "Graphic Tee", price: 14.99, material: "Cotton" },
{ name: "Joggers", price: 24.99, material: "Fleece" },
],
specialOccasion: [
{ name: "Floral Dress", price: 39.99, material: "Chiffon" },
{ name: "Bow Headband", price: 9.99, material: "Satin" },
],
};

function getItemsByOccasion(occasion) {
return clothingCollection[occasion] || [];
}

console.log(getItemsByOccasion("playtime"));

Instead of hardcoding every category, the expression:

clothingCollection[occasion]

retrieves the matching collection dynamically. If the requested category doesn't exist, the fallback returns an empty array, preventing runtime errors.

Filtering Results

Once you've selected a category, you can easily combine it with array methods.

function getCottonPlaytimeItems() {
return clothingCollection.playtime.filter(
item => item.material === "Cotton"
);
}

This pattern is useful for:

Product catalogs
E-commerce category pages
Gallery filters
Search interfaces
Inventory management systems
Dashboard filtering
Why This Pattern Works

✅ Reduces repetitive conditional logic

✅ Makes adding new categories effortless

✅ Improves code readability

✅ Scales well as your data grows

Dynamic object property access is a simple JavaScript feature that can significantly improve the structure of filtering logic. Combined with methods like filter(), map(), and reduce(), it provides a clean foundation for building maintainable applications.

How do you usually implement category filtering in JavaScript? I'd be interested to hear other approaches developers use.

#javascript #webdev #frontend #programming #coding #beginners #softwareengineering #es6 #webdevelopment

Top comments (0)