js 遍歷樹的層級關系的實現


1.遍歷樹的層級關系

1)先整理數據

2)找到id和數據的映射關系

3)然后找到父節點的數據,進行存儲

  test() {
      const list = [
        { id: "123", parentId: "", children: [] },
        { id: "124", parentId: "123", children: [] },
        { id: "125", parentId: "124", children: [] },
        { id: "126", parentId: "125", children: [] },
        { id: "127", parentId: "126", children: [] }
      ];
      const mapList = [];
      const tree = [];
      list.forEach(item => {
       
        mapList[item.id] = item;
      });
      list.forEach(item => {
        const parentNode = mapList[item.parentId];
        if (!parentNode) {
       if (!item.children) {
         item.children = []
       }
          tree.push(item);
        } else {
      if (!parentNode.children) {
        parentNode.children = []
      }
          parentNode.children.push(item);
        }
      });
      console.log("tree", tree);
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM