Powered By Blogger

Monday, April 27, 2015

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. 
 */

No comments:

Post a Comment