I am trying to use use the following JSON data to create the following similar structure in a recursive inner function with not much luck, really need some help and so if an
This solution uses a single recursive function. I simplified logic by using Array
's map()
prototype
function.
$(function () {
$("body").html(makeUnorderedList(getData().menu));
});
function makeUnorderedList(data, li) {
return $('
Here is a more dynamic approach. You get to choose how your list items are rendered and what the child property is. The mapFunc
paramater is a callback that gives you access to the current child node and its parent.
The scope of the mapFunc
is the item. So you could use item
as well as this
to refer to said item
.
$(function () {
$("body").html(makeUnorderedList(getData().menu, function(item, index, parent) {
// `item` and `this` are the same.
return $('', {
text : (item.id || item.link),
href : '#' + (item.id || item.link),
name : item.name,
'data-index' : index
});
}, 'sub'));
});
function makeUnorderedList(data, mapFunc, childProp, li, parent) {
return $('').append(data.map(function (el, index) {
var li = li || $('- ');
li.append(mapFunc.call(el, el, index, parent));
if (el[childProp]) {
li.append(makeUnorderedList(el[childProp], mapFunc, childProp, li, data));
}
return li;
}));
}