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

1.遍歷樹的層級關係spa

1)先整理數據code

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

3)而後找到父節點的數據,進行存儲it

  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 => {
        var item = {
          id: item.id,
          parentId: item.parentId,
          children: []
        };
        mapList[item.id] = item;
      });
      list.forEach(item => {
        const parentNode = mapList[item.parentId];
        if (!parentNode) {
          tree.push(item);
        } else {
          parentNode.children.push(item);
        }
      });
      console.log("tree", tree);
    },
相關文章
相關標籤/搜索