从 JSON object 生成结构化 HTML

Generating structured HTML from JSON object

我正在尝试想出从下面生成 table 的最佳方法 JSON object:

mytable=[
    {div:{
        nested:[
            {table:{
                nested:[
                    {thead:{
                        nested:[
                            {tr:{
                                nested:[
                                    {th:{}},
                                    {th:{}},
                                    {th:{}}
                                ]}}
                        ]
                    }},
                    {tbody:{}}
                ]}}
        ]}}
];

最终结果将生成 HTML 个元素,其结构如下:

<div>
    <table>
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

我的逻辑是检查 object 是否有 属性 nested 如果有则生成元素并继续循环,但是我不知道该怎么做同时将 child 元素绑定回 parents。

这样做的工作:

var mytable = /* your json */

function toHTML(j, n) {

    n = n || document.createDocumentFragment('div');
    for (var i = 0, o, l = j.length; i < l; i++) {
        for (var tag in j[i]) {
            o = document.createElement(tag);
            n.appendChild(o);
            'nested' in j[i][tag] && toHTML(j[i][tag].nested, o);
        }
    }
    return n;
}
var res = toHTML(mytable);

// now append it where needed
document.body.appendChild(res);