zoukankan      html  css  js  c++  java
  • 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);
        },
  • 相关阅读:
    三维聚源
    js--继承
    1.名字忘了
    html5--画布
    Html批量读取json
    get获取Json
    5-jQuery
    Sublime Text
    Redis,JedisPool工具类
    向指定url发送Get/Post请求
  • 原文地址:https://www.cnblogs.com/xuqp/p/10954849.html
Copyright © 2011-2022 走看看