js树形结构的相关方法

 数组转树结构

 
 /**
    * @Event 数组转树结构
    * @description: pid: parentId
    * @author: mhf
    * @time: 2023-11-01 16:06:18
    **/
export function arrayToTree(
  list,
  callback = () => {},
  props = { id: 'id', pid: 'pid', children: 'children' }
) {
  function sortArr(a, b) {
    return a.orderNum - b.orderNum;
  }
 
  list.sort(sortArr);
  const tree = [];
  const map = {};
  const listLength = list.length;
  for (let i = 0; i < listLength; i++) {
    const node = list[i];
    const nodeId = node[props.id];
    map[nodeId] = node;
    callback(node);
  }
 
  for (let i = 0; i < listLength; i++) {
    const node = list[i];
    const nodePid = node[props.pid];
    const parentNode = map[nodePid];
    if (parentNode) {
      parentNode[props.children] = parentNode[props.children] || [];
      parentNode[props.children].push(node);
    } else {
      tree.push(node);
    }
  }
 
  return tree;
}

 知道树的某一个对象的id,想要获取此id对应的整个对象

 findItemById(id, data, tagId="id", tagChildren="children") {
      for (let i = 0; i < data.length; i++) {
        if (data[i][tagId] === id) {
          return data[i]
        } else if (data[i][tagChildren]) {
          const result = this.findItemById(id, data[i][tagChildren]);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },


this.findItemById(10, this.treeData)

知道树的某一个对象的id,获取该对象的父节点的id

    findParentIdById(id, data, parentIds = [], tagId="id", tagChildren="children") {
      for (let i = 0; i < data.length; i++) {
        if (data[i][tagId] === id) {
          return parentIds
        } else if (data[i][tagChildren]) {
          const result = this.findParentIdById(id, data[i][tagChildren], [...parentIds, data[i][tagId]])
          if (result) {
            return result
          }
        }
      }
      return null
    },


this.findParentIdById(10, this.treeData)

知道id获取id所在的对象在整个树形数组中的位置

   findIndexById(data, id, parentIndex) {
      for (var i = 0; i < data.length; i++) {
        var node = data[i];
        if (node.id === id) {
          return parentIndex ? parentIndex.concat(i) : [i];
        }
        if (node.children) {
          var index = this.findIndexById(
            node.children,
            id,
            parentIndex ? parentIndex.concat(i, "children") : [i, "children"]
          );
          if (index) {
            return index;
          }
        }
      }
      return null;
    },

猜你喜欢

转载自blog.csdn.net/m0_74149462/article/details/134397524
今日推荐