'Nested category display with EJS - Nodejs

First of all sorry for my bad english. My question is I can create unlimited categories but I can't publish them on my ejs theme. For example I want to list the categories in the menu bar. I failed to do so.

Moduls : Express - Mongoose Temaplate : EJS

My sample data is like this

 <div class="col-xs-12">
        <ul class="list-group">

            // the field where I want to list the categories

        </ul>
    </div>

The codes I used while creating the categories are as follows.

function createCategory(categories,parentId = null){
const categoryList = []
let category;
if(parentId == null){
    category = categories.filter(cat => cat.parentId == undefined)
}else {
    category = categories.filter(cat => cat.parentId == parentId)
}

for(let cate of category){
    categoryList.push({
        _id : cate._id,
        name : cate.name,
        slug : cate.slug,
        children : createCategory(categories,cate._id)
    })
}
return categoryList

}

In short, what I want to do is, to be able to use my categories in my menus or lists.



Solution 1:[1]

try this.

function nestedCategories(categories, parentId = null) {
    const categoryList = [];
    let category;
    if (parentId == null) {
        category = categories.filter(cat => cat.parentId == null);
    } else {
        category = categories.filter(cat => String(cat.parentId) == String(parentId));
    }

    for (let cate of category) {
        categoryList.push({
            _id: cate._id,
            name: cate.name,
            slug: cate.slug,
            children: nestedCategories(categories, cate._id)
        })
    }
    return categoryList;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ismail Hosen