Sometimes the data from the back end is not necessarily the data we need, so we need to convert the data from the normal array structure to the tree structure ourselves.
// Array structure
let arr = [
{ id:"01".pid:"".name:"Wang" },
{ id:".".pid:"01".name:"Zhang" },
{ id:"3".pid:".".name:"Little Zhang" },
{ id:"04".pid:"".name:"Chen"},]// You want to implement it as a tree
// let arr = [
// {id:"01",pid:"",name:" ",children:[
// {id:"02",pid:"01",name:" xiaozhang ",children:[
// {id:"03", id:"02", id:"02"}]},
// ]},
// {id:"04",pid:"", id:""},
// ]
// Export the wrapped function
export function tranListToTreeData(arr) {
// Create a new array
const newArr = []
// 1. Build a dictionary to quickly find the current object by id.
/ / I hope this map is the structure of the {' 01: {id: "01", pid: ", "name:" wang "}, '02: {id: "02", pid: "01," name: "zhang"}}
const map = {}
arr.forEach( item= >{
// Add children to each item for ease of calculation
item.children = []
const key = item.id
map[key]=item
// After the above operations, the map should look like this:
/ / {' 01: {id: "01", pid: ", "name:" Lao wang, "the children: []}, '02: {id:" 02 ", pid: "01" name: "zhang", the children: []}}})// 2. Start analyzing arR
arr.forEach( item= > {
// difficult: map[item.pid] can find its parent
const parent = map[item.pid]
if (parent) {
// If it has a parent, add the current object to the children of the parent element.
parent.children.push(item)
} else {
// If it has no parent (pid: "), add it directly to newArr
newArr.push(item)
}
})
// 3
return newArr
}
Copy the code