Last active
August 29, 2015 14:19
-
-
Save svapreddy/947964ebda805b24510a to your computer and use it in GitHub Desktop.
Nested JSON to HTML Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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