Create a nested UL menu based on the URL path structure of menu items

前端 未结 6 594

I have an array of menu items, each containing Name and URL like this:

var menuItems = [  
    {  
        name : \"Store\",  
        url : \"/store\"  
          


        
6条回答
  •  孤街浪徒
    2021-01-05 08:50

    I think the best solution is firstly to convert your data structure to a tree one, with parent/children relations. Render this structure will then be easier, as the UL itself has a tree structure.

    You can convert menuItems using these couple of functions

    // Add an item node in the tree, at the right position
    function addToTree( node, treeNodes ) {
    
        // Check if the item node should inserted in a subnode
        for ( var i=0; i

    The resulting menuItemsTree will be an object like this

    [
      {
        "name":"Store",
        "url":"/store",
        "children":[
          {
            "name":"Travel",
            "url":"/store/travel",
            "children":[
    
            ]
          },
          {
            "name":"Gardening",
            "url":"/store/gardening",
            "children":[
    
            ]
          },
          {
            "name":"Healthy Eating",
            "url":"/store/healthy-eating",
            "children":[
              {
                "name":"Cook Books",
                "url":"/store/healthy-eating/cook-books",
                "children":[
    
                ]
              },
              {
                "name":"Single Meal Gifts",
                "url":"/store/healthy-eating/single-meal-gifts",
                "children":[
    
                ]
              }
            ]
          },
          {
            "name":"Outdoor Recreation",
            "url":"/store/outdoor-recreation",
            "children":[
              {
                "name":"Hiking",
                "url":"/store/outdoor-recreation/hiking",
                "children":[
                  {
                    "name":"Snowshoeing",
                    "url":"/store/outdoor-recreation/hiking/snowshoeing",
                    "children":[
    
                    ]
                  }
                ]
              },
              {
                "name":"Skiing",
                "url":"/store/outdoor-recreation/skiing",
                "children":[
    
                ]
              }
            ]
          },
          {
            "name":"Physical Fitness",
            "url":"/store/physical-fitness",
            "children":[
    
            ]
          },
          {
            "name":"Provident Living",
            "url":"/store/provident-living",
            "children":[
    
            ]
          }
        ]
      }
    ]
    

    You mentioned you already have html renderer for trees, right? If you need further help let us know!

提交回复
热议问题