统统直接上代码,拿之即用
树形转扁平
function flatten(data) {
return data.reduce((prev, cur) => {
prev.push({id: cur.id, name: cur.name });
if (cur.children) {
prev.push(...flatten(cur.children));
}
return prev;
}, []);
}
扁平转树形
function flatToTreeData(list) {
const treeList = [], map = {}
list.forEach(item => {
if (!item.children) {
item.children = []
}
map[item.id] = item
})
list.forEach(item => {
const parent = map[item.pid]
if (parent) {
parent.children.push(item)
} else {
treeList.push(item)
}
})
return treeList
}