Structure Tree Recursive Method Documentation

Structure Tree Recursive Method Documentation

In our work, we often encounter the need for structure trees, and the processing of structure trees will be more troublesome, especially when the structure returned by the backend is not the structure we want. My scenario is that the backend returns a one-dimensional array object. I need to use an associated parent id to process the data format of the structure tree. The level is uncertain. At this time, we need to use a recursive method. The following records a method of recursively recursing a one-dimensional array into a structure tree format, using GPT Hit the note, haha

init(list, permisId) {
    
    
  // 根据permisId筛选出所有父级pPermisId等于该permisId的项
  const _list = this.originallist.filter(item => item.pPermisId === permisId);
  // 如果筛选结果列表不为空,说明有子节点
  return _list.length > 0
    // 则遍历筛选结果列表中的每一项,为每个子节点添加children属性,并递归调用自身生成子节点的树形结构
    ? _list.map(item => ({
    
     ...item, children: this.init(list, item.permisId) }))
    // 如果没有子节点,返回一个空数组
    : [];
},

When calling, the value is passed for the first time, and the association id needs to be passed as undefined, because the first layer has no parent node, we need to find out the first layer first

this.init(list, undefined)

We only need to pass in our one-dimensional array, which is the original data, to get the structure of the structure tree.

Recursively mark the bottom leaf node

In our specific operation, in fact, we only need to operate the bottom leaf structure, because if the bottom leaf is checked, the parent node will also be checked. The following record is a recursive structure tree, which is marked for the leaf nodes method

flattenTree(tree, result = []) {
    
    
  // 如果传入的tree参数不存在,则直接返回结果数组result
  if (!tree) return result;
  // 遍历树结构中的每个节点,将其permisId和是否为叶子节点的状态({ permisId, leaf })添加到结果数组中
  result.push(...tree.map(node => ({
    
     permisId: node.permisId, leaf: !node.children.length })));
  // 遍历树结构中每个节点的children属性,并递归调用本函数,将结果合并进结果数组result中
  tree.forEach(node => this.flattenTree(node.children, result));
  // 返回最终结果数组
  return result;
},

Take out all the bottom leaf nodes of the structure tree

deepList(data) {
    
    
  // 遍历data数组中的每一项
  data.map(item => {
    
    
    // 如果当前项存在children属性并且该属性有子元素,则递归调用自身深度遍历该子树
    if (item.children && item.children.length > 0) {
    
    
      this.deepList(item.children);
    } else {
    
    
      // 否则,将当前项的permisId加入curkeys数组
      this.curkeys.push(item.permisId);
    }
  });
},

Guess you like

Origin blog.csdn.net/m0_52313178/article/details/130600503