Skip to content

Instantly share code, notes, and snippets.

@svapreddy
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svapreddy/947964ebda805b24510a to your computer and use it in GitHub Desktop.
Save svapreddy/947964ebda805b24510a to your computer and use it in GitHub Desktop.
Nested JSON to HTML Lists
/*Description:
* This utility can be used to generate html structure for Nested JSON structures like tree.
* You can customize this as you need to acomplish your own html structure.
* */
function toTree(data, nestedKey, transformer) {
var str = [];
var traverse = function (_obj) {
str[str.length] = "<ul>";
(function (obj) {
str[str.length] = "<li>" + transformer(obj);
var t = obj[nestedKey];
if (t instanceof Array && t.length > 0) {
for (var i = 0, l = t.length; i < l; i += 1) {
traverse(t[i]);
}
}
str[str.length] = "</li>";
})(_obj);
str[str.length] = "</ul>";
};
traverse(data);
return str.join('');
};
/*
* How to use:
* toTree(obj, nestedKey, transformer);
* please refer this demo: http://codepen.io/svapreddy/pen/YXzaXR.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment