[JS] Array and tree structure are converted to each other, and the path of the tree node is searched according to the id

Convert between array and tree structure

original array arr

const arr = [
  {
    
     id: 1, title: '中国', parentId: 0 },
  {
    
     id: 2, title: '浙江省', parentId: 1 },
  {
    
     id: 3, title: '杭州市', parentId: 2 },
  {
    
     id: 4, title: '西湖区', parentId: 3 },
  {
    
     id: 5, title: '河南省', parentId: 1 },
  {
    
     id: 6, title: '郑州市', parentId: 5 },
];

Array To Tree

/* Array To Tree */
function arrToTree(data) {
    
    
  let result = [];
  if (!Array.isArray(data)) {
    
    
    return result;
  }
  let map = new Map();
  data.forEach(item => {
    
    
    delete item.children;
    map[item.id] = item;
  });
  data.forEach(item => {
    
    
    let parent = map[item.parentId];
    if (parent) {
    
    
      (parent.children || (parent.children = [])).push(item);
    } else {
    
    
      result.push(item);
    }
  });
  return result;
}

Tree To Array

/* Tree To Array */
function treeToList(data) {
    
    
  let res = [];
  const func = (tree) => {
    
    
    tree.forEach((item) => {
    
    
      if (item.children) {
    
    
        func(item.children);
        delete item.children;
      }
      res.push(item);
    });
  };
  func(data);
  return res;
}

Find Tree Path (Level 1/Level 2)

/**
 * 根据 id 查找所在目录路径
 * @param { 树结构的数组数据 } tree 
 * @param { 要查找的 id } id 
 * @param { 初始路径 } path 
 * @returns 
 */
function parseTreePath(tree, id, path = '') {
    
    
  for (let i = 0; i < tree.length; i++) {
    
    
    let tempPath = path;
    // 避免出现在最前面的/
    tempPath = `${
      
      tempPath ? tempPath + '/' : tempPath}${
      
      tree[i].title}`;
    if (tree[i].id == id) {
    
    
      return tempPath;
    } else if (tree[i].children) {
    
    
      let reuslt = parseTreePath(tree[i].children, id, tempPath);
      if (reuslt) {
    
    
        return reuslt;
      }
    }
  }
}

parseTreePath(tree, 5)
parseTreePath(tree, 4)

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/131461884