0

What's the best way to create a nested list like this one from nested JSON objects (by list, I mean the < ol > tag or something custom with similar behaviour):

  1. Parent 1
        a. Sub 1
        b. Sub 2
             i.Sub Sub 1
             ii.Sub Sub 2
        c. Sub 3
  2. Parent 2

As an example let's use a limit of maximum 3 "nesting levels" deep.

The JSON object that would generate this list would look like this:

[
     {
         "content": "Parent 1",
         "children": [
             {
                 "content": "Sub 1",
                 "children": [...]
             },
             {
                 "content": "Sub 2",
                 "children": [...]
             }
         ]

     },
     {
         "content": "Parent 2"
     }
]
davidnagli
  • 659
  • 1
  • 6
  • 12
  • 1
    Seems like a duplicate of http://stackoverflow.com/questions/7488968/html-css-nested-options-in-a-select-field – Arun Ghosh Jul 05 '16 at 05:27

2 Answers2

0

try this simplest approach

var obj = [{
  "content": "Parent 1",
  "children": [{
    "content": "Sub 1",
    "children": [{
          "content": "sub sub 12"
     }]
  }, {
    "content": "Sub 2",
    "children": [{
          "content": "sub sub 12"
     }]
  }]

}, {
  "content": "Parent 2"
}];

var html = getListHTML(obj);
console.log( html );
$( "body" ).append( html );

function getListHTML(obj) 
{
  if ( !obj )
  {
     return "";
  }       
  var html = "<ol>";
  html += obj.map(function(innerObj) {
    return "<li>" + innerObj.content + "</li>" + getListHTML(innerObj.children)
  }).join("");
  html += "</ol>";
  return html;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can then give a different starting value (1 or a or i) based on the hierarchy level of li

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

This is a proposal with an iterative and recursive callback for Array#forEach and with proper element generating on the fly.

function getValues(el) {
    var li = document.createElement('li'),
        ol;

    li.appendChild(document.createTextNode(el.content));
    if (Array.isArray(el.children)) {
        ol = document.createElement('ol');
        el.children.forEach(getValues, ol);
        li.appendChild(ol);
    }
    this.appendChild(li);
}

var data = [{ content: 'Parent 1', children: [{ content: 'Sub 1', children: [] }, { content: 'Sub 2', children: [{ content: 'Sub Sub 1' }, { content: 'Sub Sub 2' }, ] }, { content: 'Sub 3' }] }, { content: 'Parent 2' }],
    ol = document.createElement('ol');

data.forEach(getValues, ol);
document.body.appendChild(ol);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392