2

This is my object and I want to create a menu from the submenu in it.

I am working on a project that needs to categorize the menu list groups by their parent name.

[
    {
        "parent": "Assessment",
        "name": "Assessment Due date"
    },
    {
        "parent": "Assessment",
        "name": "Grading Schemes"
    },
    {
        "parent": "Registration",
        "name": "Manual Grouping"
    }
]

I have tried the Javascript code below

jQuery(document).ready(function ($) {
    $(document).on('change','#parentMenu', function () {
        console.log("It has changed");
        var ParentMenuId = $(this).val();
        // console.log(ParentMenuId);
        $.ajax({
            type:'get',
            url: '{!! URL::route('submenu') !!}',
            data: { 'id': ParentMenuId },
            dataType:'json',
            success: function (data) {
                $("#submenulist").empty();
                data.forEach(function (element) {
                    $("#submenulist").append('<li><a href="#">'+ element.name +'</a></li>');
                })
            }
        });
    });
});

I am getting the list of the items like this

<li>Assessment Due date</li>
<li>Grading Schemes<li>
<li>Manual Grouping<li>

but I want to group it by the parent so I want to produce this

<ul>Assessment<\ul>
<li>-Assessment Due date</li>
<li>-Grading Schemes</li>
<ul>Registration</ul>
<li>-Manual Grouping</li> 

Please, any one to assist me get the menu in the form of parent and children.

Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61

1 Answers1

2

You can use reduce to group your data by parent:

const data = [
    {
        "parent": "Assessment",
        "name": "Assessment Due date"
    },
    {
        "parent": "Assessment",
        "name": "Grading Schemes"
    },
    {
        "parent": "Registration",
        "name": "Manual Grouping"
    }
];

const groupedData = data.reduce((acc, curr) => {
  (acc[curr.parent] = acc[curr.parent] || []).push(curr);
  return acc;
}, {});

console.log(groupedData);

Then you can the use groupedData to produce the menu in the way you want. If you need, you can get the parent names from groupedData by calling Object.keys(groupedData). With this, you can decide the order of the parents you want to display. You could sort them alphabetically, for example.

Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46