i trying parse json , build html string append dom no matter string returning first element in json.
here's js:
var menu_json = { "name": "personal banking", "url": "/test1.html", "children": [ { "id": "1", "name": "test2", "url": "/products/deposits/test2.html", "children": [ { "id": "1", "name": "test3", "url": "/products/deposits/test3.html", "children": [ { "id": "1", "name": "test5", "url": "test5" }, { "id": "2", "name": "test6", "url": "/products/deposits/test6.html" }, { "id": "3", "name": "test7", "url": "/products/deposits/test7.html" }, { "id": "4", "name": "test8", "url": "/products/deposits/test8.html" }, { "id": "5", "name": "test9", "url": "/products/deposits/test9.html" }, { "id": "6", "name": "test10", "url": "/products/deposits/test10.html" }, { "id": "7", "name": "test11", "url": "/products/deposits/test11.html" } ] } ] } ] } var test_html = "<ul>", buildnavhelper = function(curnode){ test_html += "<li>" + curnode.name; if (curnode.hasownproperty('children')){ test_html += "<ul>" + _.map(curnode.children, buildnavhelper) + "</ul>"; } test_html += "</li>"; }; buildnavhelper(menu_json); test_html += "</ul>"; $('#thing').append(test_html);
heres fiddle https://jsfiddle.net/w734bvw7/
buildnavhelper()
has no return statement, there's nothing coming _.map()
. outer test_html isn't in scope. try this:
buildnavhelper = function(curnode){ var test_html = "<li>" + curnode.name; if (curnode.hasownproperty('children')){ test_html += "<ul>" + _.map(curnode.children, buildnavhelper).join("") + "</ul>"; } test_html += "</li>"; return test_html; }; test_html = "<ul>" + buildnavhelper(menu_json) + "</ul>";
note addition of .join()
avoid having commas in output.
also, there's no need use underscore here; array.map()
native javascript.
buildnavhelper = function(curnode){ var test_html = "<li>" + curnode.name; if (curnode.hasownproperty('children')){ test_html += "<ul>" + curnode.children.map(buildnavhelper).join("") + "</ul>"; } test_html += "</li>"; return test_html; };