简体   繁体   中英

Creating a dynamic Navigation Menu from a very dynamic(typical JSON structure) using Javascript or Jquery or AngularJS?

I have to create a menu that is based on dynamic JSON coming from server which is something like this.

    [  
   {  
      "something":[  
         {  
            "something":[  
               "something",
               "something"
            ]
         },
         {  
            "something":[  
               "something",
               "something",
               {  
                  "something":[  
                     "something",
                     "something"
                  ]
               }
            ]
         },
         "something"
      ]
   },



   {  
      "something":[  
         "something",
         "something",
         "something"
      ]
   },


   {  
      "something":[  
         {  
            "something":[  
               {  
                  "something":[  
                     "something",
                     {  
                        "something":[  
                           "something",
                           "something"
                        ]
                     },
                     "something"
                  ]
               },
               "something",
               "something"
            ]
         },
         "something",
         "something"
      ]
   },{
     "something":[  
         "something"
      ]
   }
]
enter code here

So I tried parsing through it and then it struck me that this structure will also be dynamic in nature so my looping wont work.

I am looking for some input for developing a snippet that creates a menu dynamicaly based on JSON (also dynamic) that will be coming from server.

Use a recursive function like

function parse(object, id)
{
    if(Array.isArray(object))  //array
    {
        object.forEach(function(a){
            parse(a,id);
        });
    }
    else if(typeof object == 'object')  //JSON object
    {
        var index = 0;
        for (var k in object) {
            $(".list" + id).append("<div class='list" + id.toString() + index.toString() + "'>" + k + "</div>");
            index++;
            parse(object[k],id.toString() + index.toString());
        }
    }
    else  //string
    {
        $(".list" + id).append("<div class='list" + id.toString() + "0'>" + object + "</div>");
    }
}
parse(obj,"0");

obj is the main object with which this function is called. It recursively checks for the object type and embeds it inside divs with unique IDs.

I haven't tested it out as your object is not in correct format. Get the basics right like the keys should be unique etc. This should give you a hint on how to go ahead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM