let tree = [
{
id: 1, title: "1", children: [
{ id: 2, title: "1-1" },
{ id: 3, title: "1-2", children: [{ id: 4, title: "1-2-1", children: [{ id: 5, tile: "1-2-1-1" }] }] },
{ id: 6, title: "1-3", children: [{ id: 7, title: "1-3-1" }] },
]
},
{ id: 8, title: '2' },
{ id: 9, title: '3', children: [{ id: 10, title: '3-1' }] }
]
/**
* 树结构转扁平结构
* @param data
* @return {Array}
*/
function transformTreeToFlat(data) {
const cloneData = JSON.parse(JSON.stringify(data))
let result = []
function fn(array) {
for (let i of array) {
result.push(i)
if (i.children && i.children.length !== 0) {
fn(i.children)
delete i.children
}
}
}
fn(cloneData)
return result
}
console.log(transformTreeToFlat(tree))
const list = [{ id: 1, name: '司令', pid: 0 }, { id: 2, name: '军长', pid: 1 }, { id: 3, name: '副军长', pid: 1 }, { id: 4, name: '旅长', pid: 3 }, { id: 5, name: '团长', pid: 4 },]
/**
* 扁平结构转树结构
* @param data
* @return {*} 含children的树形结构
*/
function transformFlatToTree(data) {
const cloneData = JSON.parse(JSON.stringify(data))
function getTreeList(rootList, pid, list) {
// 初始化第一层节点
for (let item of rootList) {
if (item.pid === pid) {
list.push(item)
}
}
// 递归子节点
for (let i of list) {
i.children = []
getTreeList(rootList, i.id, i.children)
if (i.children.length === 0) {
delete i.children
}
}
return list
}
return getTreeList(cloneData, 0, [])
}
console.log(transformFlatToTree(list))
function arrToTree(list) {
// 定义最终需要返回的树形结构数据
let treeData = []
// 对传入的数组进行遍历
list.forEach(item => {
// 如果pid没有值,那就是顶级对象,直接添加进数组
if (!item.pid) { treeData.push(item) }
// 理解为二次遍历 :每个对象都找一遍自己的孩子添加到children
let objList = list.filter(data => data.pid === item.id)
if (objList.length) { item.children = objList }
})
return treeData
}
console.log(arrToTree(list));
/**
* 根据index删除节点
* @param arr 树形tableList数据
* @param index 所在tableList
*/
function deleteNodeByIndex(arr, index) {
let count = 0
let returnFlag = false
function fn(arr) {
for (let i = 0; i < arr.length; i++) {
if (returnFlag) {
// 终止递归
return
}
if (count === index) {
arr.splice(i, 1)
returnFlag = true
return
}
count++
if (arr[i].children && arr[i].children.length !== 0) {
fn(arr[i].children)
}
}
}
fn(arr)
}
console