List categories and show subcategories when select category with json

I made a page like this with json. I added my test example the link at the bottom of the article. I listed the categories in this way with json. But there is something else I want. After selecting the category, I want to show the subcategories of the selected category on the screen, on the same page, maybe in the same area. How can I do this?

these are the codes I added as an example. You can see the site I prepared at the bottom of the article.

So actually when the category is selected, I want to show subcategory on the screen.

HTML

<ul id="category" class="grid">
</ul>

JAVASCRÄ°PT

$(function() {

    var people = [];
    $.getJSON("category.json", function (data) {
        $.each(data.cat_en, function(i, f) {
        var tblRow = '<li class="grid_item">' + '<a href="' + f.cat_url +'">'+ '<div>'+'<div>'+'</img>'+'</div>'+ '<div>'+ f.cat_name + '<span>'+ f.cat_product_count +'</span>' + '</div>'+ '</div>'+'</a>'+'</li>' 
        
        $(tblRow).appendTo("#category")
        })
    })
})

JSON

{
    "cat_en" : 
    [
        {
          "cat_name": "Aluminum Components",
          "cat_url": "#",
          "cat_product_count": 29
        },
        {
          "cat_name": "Gas Springs",
          "cat_url": "#",
          "cat_product_count": 75
        },
        {
          "cat_name": "Lighting Parts",
          "cat_url": "#",
          "cat_product_count": 271
        },
        {
          "cat_name": "Rear View Mirrors And Components",
          "cat_url": "#",
          "cat_product_count": 71
        },
        {
          "cat_name": "Freezer And Components",
          "cat_url": "#",
          "cat_product_count": 22
        },
        {
          "cat_name": "Upholstery fabrics",
          "cat_url": "#",
          "cat_product_count": 13
        }
    ]
}

demo site

enter image description here

33 thoughts on “List categories and show subcategories when select category with json”

  1. If we assume subcategories stored in each object,

    {
        "cat_name": "Aluminum Components",
        "cat_url": "#",
        "cat_product_count": 29,
        "subcats": [
            {
              "cat_name": "First Subcategory",
              "cat_url": "#"
            },
            {
              "cat_name": "Second Subcategory",
              "cat_url": "#"
            }
        ]
    }
    

    You may try to implement that function to your code (I don’t know JQuery so I wrote in vanilla JS);

    (categoryObject) => {
        if (categoryObject.subcats.length > 0) {
            categoryObject.subcats.forEach(
                (subCategoryObject) => {
                    template = `<li class="subcategory"><a href="${subCategoryObject.cat_url}">${subCategoryObject.cat_name}</a></li>\n`
                    return template
                }
            )
        }
    }
    
    Reply

Leave a Comment