1. Array conversion number structure
Let data= [{id: 2, name: 'department B', parentId: 0}, {id: 3, name:' department C', parentId: 1}, {id: 1, name: 'department A', parentId: 1} 2}, {id: 4, name: 'department D', parentId: 1}, {ID: 5, name:' department E', parentId: 2}, {id: 6, name: 'department F', parentId: 2}, {id: 6, name:' department F', parentId: 3}, {id: 7, name: 'department G', parentId: 2}, {= ID: 8, name:' department H', parentId: 4}, {id: 9, name: 'department I', parentId: 8}]; function transTree(data) { let result = [] let map = {} if (! Array.isarray (data)) {return []} data.forEach(item => {map[item.id] = item }) data.foreach (item => {let parent = map[item.parentid] // Find the parent of each item in data if (parent) { Put the elements under the father of the children (parent. Children | | (parent. Children = [])). Push (item)} else {/ / that elements have no dad, is the root node, Result.push (item) //item is a reference to the object}}) return result // Objects in the array are shared with data} console.log(transTree(data))Copy the code
2. Convert the tree structure into an array
Function transArr(node) {let queue= [node] let data = [] while (queue.length! Data. push({id: item.id, parentId: item.parentId, name: {id: item.id, parentId: item.parentId, name: Item.name}) let children = item.children if (children) {for (let I = 0; i < children.length; I ++) {queue.push(children[I]) // Add children to queue end}}} return data} console.log(transArr(node))Copy the code