I have an SQL dataset that will change frequently, and I need to regularly create nested unordered lists. I converted the SQL data into an array of objects, but I was fixated on the logic to create an unordered list.
I tried to make a recursive function, but I do not experience this enough, therefore
The data contains the following fields:
ID Category Name ParentID
Thus, each category has an identifier and a ParentID (which corresponds to the identifier of another category). All root categories have the same dummy ParentID.
The javascript object has the same properties. Here is an example:
var Categories = [ new Category(1, 'Root', 0), new Category(2, 'Cat1', 1), new Category(3, 'Cat2', 2), new Category(4, 'Cat3', 5), new Category(5, 'Cat4', 1), new Category(6, 'Cat5', 5), new Category(7, 'Cat6', 5), new Category(8, 'Cat7', 1), new Category(9, 'Cat8', 2), new Category(10, 'Cat9', 1), new Category(11, 'Cat10', 10), new Category(12, 'Cat11', 1), new Category(13, 'Cat12', 8) ]
I need to use this array of objects to make an unordered list that will look like this:
<ul> <li>Cat1 <ul> <li>Cat2</li> <li>Cat8</li> </ul> <li>Cat4 <ul> <li>Cat3</li> <li>Cat5</li> <li>Cat6</li> </ul> </li> <li>Cat7 <ul> <li>Cat12</li> </ul> </li> <li>Cat8</li> <li>Cat9 <ul> <li>Cat10</li> </ul> </li> <li>Cat11</li> </ul>
At present, my deepest data is 3 levels, but I would like to be able to script to do any number of levels.
jQuery is suitable for this.