This hierarchy of traversing the tree js

1. hierarchy tree traversal

1) Organize your data

2) find a mapping between id and data

3) Then find the parent node data, stores

  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);
    },

 

Guess you like

Origin www.cnblogs.com/xuqp/p/10954849.html