通过使用字符串问题解析对象来显示树结构

时间:2017-03-25 21:15:24

标签: javascript

我想解析一个对象并以树状结构打印。我在处理(privateJet和Ship)时遇到了问题。我想在递归函数中做到这一点。

对象

[{"land":[{"vehicles":["car","bus","train"]}]},{"air":[{"commercial":[{"flight":["local","international"]},"privateJet"]},"ship"]}]

我得到了什么:

enter image description here

代码:

<!doctype html>
<html>
<body>
<div id="abc"></div>

<script>
var treeObj = [{"land":[{"vehicles":["car","bus","train"]}]},{"air":[{"commercial":[{"flight":["local","international"]},"privateJet"]},"ship"]}]

function createTree(obj, parent) {
    for(key in obj) {
        if(typeof obj[key] == 'string') {
            document.getElementById('abc').innerHTML += '<div style="padding-left:10em">' + obj[key] + '</div>';
        } else {
            console.log(key, obj);
            x = 1;
            for(categoryKey in obj[key]) {

                var category = obj[key];
                if(Object.prototype.toString.call( category[categoryKey] ) === '[object Array]') {
                    document.getElementById('abc').innerHTML += '<div style="padding-left:'+ (parent * 5) +'em">' + categoryKey;
                    createTree(category[categoryKey], x);
                    document.getElementById('abc').innerHTML += '</div>';
                }
                x++;
            }
        }
    }
}

createTree(treeObj, 0);

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

使用适当的对象,您可以构建新的无序列表和列表项。

&#13;
&#13;
var data = [{ land: [{ vehicles: ["car", "bus", "train"] }] }, { air: [{ commercial: [{ flight: ["local", "international"] }, "privateJet"] }] }, { sea: ["ship"] }];

document.body.appendChild(data.reduce(function getValues(ul, el) {
    var li = document.createElement('li'),
        key;

    if (typeof el === 'object') {
        key = Object.keys(el)[0];
        li.appendChild(document.createTextNode(key));
        if (Array.isArray(el[key])) {
            li.appendChild(el[key].reduce(getValues, document.createElement('ul')));
        }
    } else {
        li.appendChild(document.createTextNode(el));
    }
    ul.appendChild(li);
    return ul;
}, document.createElement('ul')));
&#13;
&#13;
&#13;