1. 数据结构
a. 树形结构
const treeStructure = {
name: Id,
children: [treeStructure],
}
实例
const treeData = {
name: 1,
children: [{
name: 2,
children: [{
name: 4,
children: [{
name: 7,
children: [{
name: 8,
children: []
}, {
name: 9,
children: []
}]
}],
}, {
name: 5,
children: [],
}]
}, {
name: 3,
children: [{
name: 6,
children: [],
}],
}],
}
b. 数组结构
[{
name: Id,
children: [Id],
}]
实例输出结果
[
{ name: 1, children: [ 2, 3 ] },
{ name: 2, children: [ 4, 5 ] },
{ name: 4, children: [ 7 ] },
{ name: 7, children: [ 8, 9 ] },
{ name: 8, children: [] },
{ name: 9, children: [] },
{ name: 5, children: [] },
{ name: 3, children: [ 6 ] },
{ name: 6, children: [] }
]
2. 算法实现
function transfer(treeData) {
if (!(!treeData.hasOwnProperty('name') || !treeData)) {
let arr = []
let obj = {}
obj.name = treeData.name
obj.children = treeData.children.map(value => {
return value.name
})
arr.push(obj)
treeData.children.forEach(value => {
arr = arr.concat(transfer(value))
})
return arr
} else {
return []
}
}
const arrayData = transfer(treeData);
console.log(arrayData)
js将数组转为树形结构