Analysis of the Implementation Principle of JS Traversal Tree Hierarchical Relationship

  • 2021-08-09 07:05:35
  • OfStack

1. Traverse the hierarchical relationship of the tree

1) Collate the data first

2) Find the mapping relationship between id and data

3) Then find the data of the parent node and store it

The code is as follows


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

Related articles: