多级嵌套对象数组:根据最里层id找出它所属的每层父级,适用于树形数据格式

文章目录

需求

已知一个树形格式数据如下:

// 示例数据
const data = [
  {
    "id": "1",
    "parentId": null,
    "children": [
      {
        "id": "1.1",
        "parentId": "1",
        "children": [
          {
            "id": "1.1.1",
            "parentId": "1.1",
            "children": []
          }
        ]
      },
      {
        "id": "1.2",
        "parentId": "1",
        "children": []
      }
    ]
  }
];

现需生成 [{parent:"1.1,children:["1.1.1","1.1.2"]}]的格式

分析

function findHierarchy(data, targetId) {
  // 定义一个辅助函数,用于递归查找父级对象
  function findParent(data, parentId) {
    for (const item of data) {
      if (item.id === parentId) {
        return item;
      }
      if (item.children && item.children.length > 0) {
        const parent = findParent(item.children, parentId);
        if (parent) {
          return parent;
        }
      }
    }
    return null;
  }

  // 定义一个辅助函数,用于递归生成父级对象
  function generateHierarchy(data, targetId) {
    const parent = findParent(data, targetId);
    if (parent) {
      const newObj = { id: parent.id };
      if (parent.parentId) {
        newObj.parent = generateHierarchy(data, parent.parentId);
      }
      return newObj;
    }
    return null;
  }

  // 调用辅助函数生成层级结构
  return generateHierarchy(data, targetId);
}

// 示例数据
const data = [
  {
    "id": "1",
    "parentId": null,
    "children": [
      {
        "id": "1.1",
        "parentId": "1",
        "children": [
          {
            "id": "1.1.1",
            "parentId": "1.1",
            "children": []
          }
        ]
      },
      {
        "id": "1.2",
        "parentId": "1",
        "children": []
      }
    ]
  }
];

// 测试函数
const targetId = "1.1.1";
const hierarchy = findHierarchy(data, targetId);
console.log(hierarchy);

上面的代码定义了一个 findHierarchy 函数,该函数接收一个多级嵌套的对象数组 data 和一个目标 ID targetId。函数首先定义了两个辅助函数 findParent 和 generateHierarchy,分别用于递归查找父级对象和递归生成父级对象。然后,调用 generateHierarchy 函数生成层级结构,并返回结果。

  • 输出格式如下
    在这里插入图片描述

接下来,我们需要继续处理,将生成的该格式数据转换成我们所需要的格式,逻辑如下

function processArray(array) {
    const result = [];
    const map = new Map();

    array.forEach(item => {
        const parentName = item.parent.name;
        const childName = item.name;

        if (!map.has(parentName)) {
            map.set(parentName, { parent: parentName, children: [] });
        }

        map.get(parentName).children.push(childName);
    });

    map.forEach(value => {
        result.push(value);
    });

    return result;
}

console.log(processArray(array));
  • 最终输出结果为:
    在这里插入图片描述
    页面上展示效果如下
    在这里插入图片描述
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>水位绘制</title>
  
<style>
  .water-level {
    width: 200px;
    /* 水位计的宽度 */
    height: 300px;
    /* 水位计的高度 */
    border: 2px solid #ccc;
    /* 水位计的边框样式 */
    position: relative;
  }

  .container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .water {
    background-color: blue;
    /* 水的颜色 */
    position: absolute;
    bottom: 0;
    width: 100%;
    transition: height 0.5s ease;
    /* 过渡动画效果 */
  }

  .water-level-mark {
    position: absolute;
    top: calc(100% - 20px);
    /* 水位标识线的位置,这里假设水位标识线距离底部20像素 */
    width: 100%;
    height: 2px;
    /* 水位标识线的高度 */
    background-color: red;
    /* 水位标识线的颜色 */
  }
</style>

</head>

<body>
<div class="water-level">
  <div id="list"></div>
</div>

  <script>
    // 获取导航栏中的所有链接
    var navLinks = document.querySelectorAll('.new-navbar li a');

    // 切换导航栏样式的函数
    function toggleNav (index) {
      // 先移除所有链接的 'active' 类
      navLinks.forEach(link => link.classList.remove('active'));
      // 给点击的链接添加 'active' 类
      navLinks[index].classList.add('active');
    }
    function findHierarchy (data, targetId) {
        // 定义一个辅助函数,用于递归查找父级对象
        function findParent (data, parentId) {
          for (const item of data) {
            if (item.id == parentId) {
              return item;
            }
            if (item.children && item.children.length > 0) {
              const parent = findParent(item.children, parentId);
              if (parent) {
                return parent;
              }
            }
          }
          return null;
        }

        // 定义一个辅助函数,用于递归生成父级对象
        function generateHierarchy (data, targetId) {
          const parent = findParent(data, targetId);
          if (parent) {
            const newObj = { id: parent.id };
            if (parent.parentId) {
              newObj.parent = generateHierarchy(data, parent.parentId);
            }
            return newObj;
          }
          return null;
        }

        // 调用辅助函数生成层级结构
        return generateHierarchy(data, targetId);
      }

      // 示例数据
      const data = [
        {
          "id": "1",
          "parentId": null,
          "children": [
            {
              "id": "1.1",
              "parentId": "1",
              // "children": [
              //   {
              //     "id": "1.1.1",
              //     "parentId": "1.1",
              //     "children": []
              //   }
              // ]
            },
            {
              "id": "1.2",
              "parentId": "1",
              "children": []
            }
          ]
        }
      ];

      // 测试函数
      const targetId = "1.1";
      const hierarchy  = [];
      hierarchy.push(findHierarchy(data, targetId))
      console.log(hierarchy)
      // 格式化函数
      function processArray (array) {
        const result = []
        const map = new Map()

        array.forEach(item => {
          const parentName = item.parent.id
          const childName = item.id

          if (!map.has(parentName)) {
            map.set(parentName, { parent: parentName, children: [] })
          }

          map.get(parentName).children.push(childName)
        })

        map.forEach(value => {
          result.push(value)
        })

        return result
      }

  let parentChildList = processArray(hierarchy)
  // 使用原生的模板字符串创建 HTML 字符串
    let htmlString = "<ul>";
    parentChildList.forEach(item => {
      htmlString += `<li>${item.parent}----${item.children}</li>`;
    });
    htmlString += "</ul>";

    // 将 HTML 字符串插入到 DOM 中
    document.getElementById("list").innerHTML = htmlString;
  </script>

</body>

</html>

最近更新

  1. TCP协议是安全的吗?

    2024-04-24 21:14:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-24 21:14:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-24 21:14:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-24 21:14:02       20 阅读

热门阅读

  1. Bash 脚本常用命令

    2024-04-24 21:14:02       10 阅读
  2. Docker之构建镜像

    2024-04-24 21:14:02       10 阅读
  3. SqL--DCL数据控制语言

    2024-04-24 21:14:02       12 阅读
  4. ES是什么?ES的使用场景有哪些?分词器??

    2024-04-24 21:14:02       12 阅读
  5. Python常见运算符

    2024-04-24 21:14:02       12 阅读