This is going to be a bit long winded, but here goes:
I am writing two separate web applications: one for generating a JSON object with a bunch of data and formatting information and another for turning that JSON object into a nice formatted HTML page for viewing. The particular issue I am having currently is with nested lists.
For the viewing application, I wrote a recursive function that will parse the supplied javascript object and create the HTML for a list with an arbitrary magnitude of nested elements.
function createUnorderedList(object) {
var ul = $('<ol>');
for (var i = 0; i < object.length; i++) {
if (object[i].children === undefined) {
ul.append($('<li>').text(object[i].value));
} else {
ul.append(
$('<li>').html(
object[i].value + "<ul>" + createUnorderedList(object[i].children) + "</ul>"));
}
}
return ul.html();
}
The jsfiddle for that function can be seen here: jsfiddle: Recursive HTML List Generation
Now, I need to create a function for the JSON creation side of things. Having tried and failed to wrap my brain around how to do this recursively, I settled upon a more linear function, seen here:
function createList( array ) {
var json = { "value": [] } ;
var k = 0 ;
if(array[array.length-1] === "") array.pop() ;
for(var i=0; i<array.length; i++ ){
json.value.push( { "value": array[i] } ) ;
for(var j=i+1; j<array.length; j++) {
if(array[j].charAt(0) === '\t') {
array[j] = array[j].replace( /\t/, '' ) ;
i++;
if(json.value[k].children === undefined)
$.extend( json.value[k], { children : [] } ) ;
json.value[k].children.push( { "value": array[j] } ) ;
} else { k++; j=array.length; }
}
}
return json ;
}
jsfiddle: JSON List Generation.
This function can only handle a nested list of one order of magnitude, which should suffice for now but is not ideal. How can I make this function capable of generating a json object with an arbitrary magnitude of nested elements?
Thank you.
Array.prototype.reduce(). SeemakeOrderedList3() in my example.