As the input, I have an array of objects. I need to loop through it and display the table as shown below:
const arr = [
{
name: 'home/',
children: [
{
name: 'test1',
children: [
{
name: 'test3',
children: []
}
]
},
{
name: 'test2',
children: []
}
]
}
]
| | test1 | test3 |
| home | | |
| | test2 | |
You may try by nested tables. You can also try borders on tr
or td
elements when border-collapse: collapse
is set on the table
element CSS.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.