javascript - Nested JSON Objects Within JSON Object -
i'm trying build menu dynamically , i'm going output data json object of following form.
"link 1": { "href":"#", "sub link 1": { "href":"#" }, "sub link 2": { "href":"#", "sub sub link 1": { "href":"#" }, "sub sub link 2": { "href":"#" } } }
firs of all, i'd know if that's design link hierarchy.
on other hand, when i'm iterating on array, i'm able name "link 1" not of properties underneath link hierarchy.
the loop i'm using following one:
for(var item in jsonmenu) { console.log(item) }
it outputs: link 1, link 2, link 3
want able access other json objects inside object.
i tried nesting loop numbers : 0, 1, 2, 3
suspect length of string.
i tried using:
item.hasownproperty(key)
but doesn't work: returns uncaught reference error: key not exist
any appreciated
edit:
this far have, seems me overhead menu, far has execution time of o(n^2) , still need go 1 level deep, execution time of o(n^3):
for(var item in jsonmenu) { if(jsonmenu.hasownproperty(item)) { for(var attr in jsonmenu[item]) { console.log(attr); } console.log(item + " => " + jsonmenu[item]) } }
building on paul's answer here function renders json menu (demo):
<ul id='menu'></ul> <script> var links = { "name": "link 1", "href": "#link1", "children": [{ "name": "sub link 1", "href": "#sublink1" }] }, render = function (parent, link) { var element = $("<li><a href='" + link.href + "'>" + link.name + "</a></li>"), sublist, child; if (link.hasownproperty('children') && link.children.length > 0) { sublist = $("<ul></ul>"); (child = 0; child < link.children.length; child++) { render(sublist, link.children[child]); } element.append(sublist); } parent.append(element); }; render($('#menu'), links); </script>
Comments
Post a Comment