初始数据[数组转Tree]
let arr = [
{ id: 1, name: "小A", parent: 0 },
{ id: 2, name: "小B", parent: 0 },
{ id: 3, name: "小C", parent: 1 },
{ id: 4, name: "小D", parent: 3 },
{ id: 5, name: "小E", parent: 4 },
{ id: 6, name: "小F", parent: 2 },
{ id: 7, name: "小G", parent: 6 },
{ id: 8, name: "小H", parent: 7 },
{ id: 9, name: "小T", parent: 8 },
{ id: 10, name: "小X", parent: 4 },
]
1. 递归
function ArrayToTree (arr, parent = 0) {
if (!Array.isArray(arr) || !arr.length) return [];
let newArr = []
arr.forEach(item => {
if (item.parent == parent) {
const res = ArrayToTree(arr, item.id)
if (res.length) {
newArr.push({
...item,
children: res
})
} else {
newArr.push({
...item
})
}
}
})
return newArr
}
2.双重循环
function arrToTreeOne (arr, parent = 0) {
if (!Array.isArray(arr) || !arr.length) return [];
let copyArr = Object.assign([], arr)
let newArr = copyArr.filter(item => {
arr.forEach(v => {
if (item.id === v.parent) {
if (item.children) {
item.children.push(v)
} else {
item.children = [v]
}
}
})
if (item.parent == parent) return item
})
return newArr
}
3.map
function ArrAyToTreeMap (arr, parent = 0) {
if (!Array.isArray(arr) || !arr.length) return [];
let map = {}
arr.forEach(item => map[item.id] = item)
let res = []
arr.forEach(item => {
let mapPid = map[item.parent]
if (item.parent == parent) {
res.push(item)
} else {
if (mapPid) {
((mapPid.child || (mapPid.child = [])).push(item))
}
}
})
return res;
}
4.过滤器
function arrToTreeArray (arr, parent = 0) {
if (!Array.isArray(arr) || !arr.length) return [];
let copyArr = arr.filter(item => {
let children = arr.filter(v => item.id === v.parent)
item.children = children.length > 0 ? item.children = children : []
if (item.parent == parent) {
return item
}
})
return copyArr
}
数组转Tree
function TreeToArray (tree) {
if (!Array.isArray(tree) || !tree.length) return []
let res = []
tree.forEach(v => {
const { children, ...v2 } = v
res.push(v2)
if (v.children) {
res.push(...TreeToArray(v.children))
}
})
return res
}