【问题标题】:Display nested html table looping through the nested array of objects显示嵌套的 html 表格循环遍历对象的嵌套数组
【发布时间】:2021-12-29 18:22:21
【问题描述】:

作为输入,我有一个对象数组。我需要遍历它并显示如下所示的表格:

const arr = [
  {
    name: 'home/',
    children: [
      {
        name: 'test1',
        children: [
          {
            name: 'test3',
            children: []
          }
        ]
      },
      {
        name: 'test2',
        children: []
      }
    ]
  }
]

|      | test1 | test3 |
| home |       |       |
|      | test2 |       |

 

【问题讨论】:

  • 欢迎来到 Stack Overflow!这是一个用于询问需要特定答案的技术问题的网站,而不是让人们为您编写代码。

标签: javascript html loops


【解决方案1】:

您可以尝试嵌套表格。当border-collapse: collapse 设置在table 元素CSS 上时,您还可以尝试在trtd 元素上设置边框。

var arr = [ { name: 'home/'
            , children: [ { name: 'test1'
                          , children: [ { name: 'test3'
                                        , children: []
                                        }
                                      ]
                          }
                          ,
                          { name: 'test2'
                          , children: []
                          }
                        ]
            }
          ];
function makeTable(rows){
  return new DocumentFragment().appendChild(rows.reduce(function(t,r){
                                                          var tr = document.createElement("tr"),
                                                              td = document.createElement("td");
                                                          t.appendChild(tr)
                                                           .appendChild(td)
                                                           .append(r.name);
                                                          r.children.length && tr.appendChild(makeTable(r.children))
                                                          return t;
                                                        }, document.createElement("table")))
}
document.getElementById("container")
        .appendChild(makeTable(arr));
table {
  border: 1px solid black;
}
<div id="container"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多