Recently, I have been developing a permission management module for a backend management system, which involves data processing logic of various tree structures, such as: addition, deletion, modification, query, etc.; compared with ordinary Array structure data, the processing of tree structure is not as intuitive as array, but it is not that complicated. It requires one more step - recursive search to perform deep traversal of data. So here, the blogger will also summarize the development process I’ll share the method I came up with. This article will give you a thorough understanding of JS tree structure data processing:
Data structure example
let data = [{ id: 1, label: 'Level 1', children: [{ id: 4, label: 'Level 1-1', children: [{ id: 9, label: 'Level 3 1-1-1' }, { id: 10, label: 'Level 3 1-1-2' }] }] }, { id: 2, label: 'Level 2', children: [{ id: 5, label: 'Level 2-1' }, { id: 6, label: 'Level 2-2' }] }, { id: 3, label: 'Level 3', children: [{ id: 7, label: 'Level 2 3-1' }, { id: 8, label: 'Level 3-2' }] }];
to find the specified node in the tree structure and add a new child node. The code is as follows:
const appendNodeInTree = (id, tree, obj) => { tree.forEach(ele=> { if (ele.id === id) { ele.children ? ele.children.push(obj) : ele.children = [obj] } else { if (ele.children) { appendNodeInTree(id, ele.children, obj) } } }) return tree }
Find the specified node in the tree structure and delete the node. The code is as follows
const removeNodeInTree=(treeList, id)=> { // Remove elements from the array (tree structure) by id if (!treeList || ! treeList.length) { return } for (let i = 0; i < treeList.length; i++) { if (treeList[i].id === id) { treeList.splice(i, 1); break; } removeNodeInTree(treeList[i].children, id) } }
to recursively search and modify the status of a node. The code is as follows:
const updateNodeInTree=(treeList,id, obj)=> { if (!treeList || !treeList.length) { return; } for (let i = 0; i < treeList.length; i++) { if (treeList[i].id == id) { treeList[i]= obj; break; } updateNodeInTree(treeList[i].children,id,obj); } }
recursively to find a node in the tree node, code:
const findNodeInTree = (data, key, callback) => { for (let i = 0; i < data.length; i++) { if (data[i].key == key) { return callback(data[i], i, data) } if (data[i].children) { findNodeInTree (data[i].children, key, callback) } } } //The method to store the found node let Obj={} findNodeInTree(data, key, (item, index, arr) => { Obj = item }) // This is the node to be found corresponding to Obj console.log(Obj)