Skip to content

Instantly share code, notes, and snippets.

@danschumann
Last active August 29, 2015 13:57
Show Gist options
  • Save danschumann/9708266 to your computer and use it in GitHub Desktop.
Save danschumann/9708266 to your computer and use it in GitHub Desktop.
recursive menu
var
html, printRecord, entry, n;
// records is an array of objects with parent_id, name and id attributes
// [ {parent_id: ..., id: ..., name: ...}, ...]
html = '';
printRecord = function(parent_id){
html +='<ul>';
for (n = 0; n < records.length; n ++){
entry = records[n];
// only the ones nested under the current parent
if (entry.parent_id == parent_id) {
html += '<li>' + entry.name;
// recursively print another ul inside this li
printRecord(entry.id);
html += '</li>';
}
}
html +='</ul>';
}
printRecord(); // first record has no parent, it is top
// records would print
// <ul>
// <li>name
// <ul>
// <li>subname<ul></ul></li>
// </ul>
// </li>
// </ul>
// the empty ul inside could be taken out if you check that there are children first
@danschumann
Copy link
Author

just an example, not to be used in production

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment