0

Wanted to get some input into a little problem I encounted.

What I'm trying to do

enter image description here

Data is being fetched using a headless CMS. The green are buttons/links that will scroll down to the corresponding section/category.

The goal is to add an element whether it be an (h3 or a div with a rule) with the category title followed by all the items in that category.

If the category changes, category element should be added to the DOM with the corresponding name followed by all the items belonging to that category.

What I have tried

My first approach was to use an if statement

let data = results.map( (item, iterator, theArray) => {
   let insertToHTML;

   if(item.category !== theArray[i -1 ].category) {
    insertToHTML = `<div class="category-name"> ${item.category} </div>`
   }
   return insertToHTML;
  })

document.querySelector("#product-container").innerHTML = data;

enter image description here

This quickly became a bad option. If items are updated out of order you'll have a section created with just one or two items.. It could also be a duplicate of a pre existing category.

Moving forward

I'm sure there are other ways to do this. But I'm not familiar with a pattern for this yet

Another option i thought up was to have multiple ajax/fetch requests for each section, with the html for the sections hard coded but then this page won't be 100% dynamic... not good.

My last and final option is to query the cms by category and list all the products in that category, rather than fetching products and trying to list categories.

Appreciate any input

Community
  • 1
  • 1
Mike
  • 253
  • 1
  • 6
  • 17
  • 1
    How about grouping by `category` and displaying section only if category has data. [Read about grouping here](https://stackoverflow.com/a/40774906/11719787) – Sameer May 15 '20 at 02:34
  • @SameerKhan hey yeah in the post i said that would be my last option. I think it's the easiest approach – Mike May 15 '20 at 02:45

0 Answers0