测试数据Mock
var tree = [
{
id: '11111',
name: '王秀夫10',
childrens: [
{id: '11111-0', name: '王秀夫101',childrens: [
{id: '111112-0', name: '王秀夫1011'},
{id: '111112-0', name: '王秀夫1011'},
{id: '111112-0', name: '王秀夫1011'}
]},
{id: '11111-1', name: '王秀夫12',childrens: [
{id: '111112-0', name: '王秀夫121'}
]},
{id: '11111-2', name: '王秀夫13',childrens: [
{id: '111112-0', name: '王秀夫131'},
{id: '111112-0', name: '王秀夫132'}
]},
{id: '11111-3', name: '王秀夫14',childrens: [
{id: '111112-0', name: '王秀夫141'}
]},
{id: '11111-4', name: '王秀夫15',childrens: [
{id: '111112-0', name: '王秀夫151'},
{id: '111112-0', name: '王秀夫152'}
]}
]
},
{
id: '11111',
name: '王秀夫20',
childrens: [
{id: '11111-0', name: '王秀夫201',childrens: [
{id: '111112-0', name: '王秀夫2011'}
]},
{id: '11111-1', name: '王秀夫202',childrens: [
{id: '111112-0', name: '王秀夫2021'}
]},
{id: '11111-2', name: '王秀夫203',childrens: [
{id: '111112-0', name: '王秀夫231'}
]},
{id: '11111-3', name: '王秀夫204',childrens: [
{id: '111112-0', name: '王秀夫2041'}
]},
{id: '11111-4', name: '王秀夫205',childrens: [
{id: '111112-0', name: '王秀夫2051'}
]}
]
}
]
转换代码
var htmls = [['<tr>', '</tr>']]
var childrensFeild = 'childrens'
function getChildrenCount(node){
var r = node[childrensFeild]
var c = (r || []).length
var res = c === 0 ? 1 : 0
for (let index = 0; r && r.length && index < r.length; index++) {
res = res + getChildrenCount(r[index])
}
return res
}
function tree2HtmlTable(treeDatas){
for (let index = 0; index < treeDatas.length; index++) {
const element = treeDatas[index];
var childCount = getChildrenCount(element)
var name = element.name
if (index === 0){
var _row = htmls[htmls.length - 1]
if (childCount > 0){
_row.splice(_row.length - 1, 0, `<td rowspan=${childCount}>${name}</td>`)
} else {
_row.splice(_row.length - 1, 0, `<td>${name}</td>`)
}
tree2HtmlTable((element[childrensFeild] || []))
continue
}
htmls.push(['<tr>', '</tr>'])
var _row = htmls[htmls.length - 1]
if (childCount > 0){
_row.splice(_row.length - 1, 0, `<td rowspan=${childCount}>${name}</td>`)
} else {
_row.splice(_row.length - 1, 0, `<td >${name}</td>`)
}
tree2HtmlTable((element[childrensFeild] || []))
}
}
tree2HtmlTable(tree, 0)
console.log('<table border=1 style="width: 400px">' + htmls.map(function(item){return item.join('')}).join('') + '</table>')