zoukankan      html  css  js  c++  java
  • 一维数组转树形结构

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>tree</title>
      </head>
    
      <body>
        <script>
          const data = [
            { id: 1, pid: 0, name: '1' },
            { id: 2, pid: 1, name: '1_1' },
            { id: 3, pid: 1, name: '1_2' },
            { id: 4, pid: 2, name: '1_1_1' },
            { id: 5, pid: 2, name: '1_1_2' },
          ]
          function toTree(data, id = 'id', pid = 'pid') {
            const result = []
            const map = {}
            if (!Array.isArray(data)) {
              return result
            }
            data.forEach((item) => {
              delete item.children
            })
            data.forEach((item) => {
              map[item[id]] = item
            })
            data.forEach((item) => {
              const parent = map[item[pid]]
              if (parent) {
                // add parent
                if (!parent.children) {
                  parent.children = []
                }
                // add level
                if (!parent.level) {
                  parent.level = 1
                }
                item.level = parent.level + 1
                parent.children.push(item)
              } else {
                result.push(item)
              }
            })
            return result
          }
          console.log(toTree(data))
        </script>
      </body>
    </html>
    
    
  • 相关阅读:
    Java内存区域
    spring学习之Bean
    记一次日本公司的Java面试
    java中打印输出数组内容的三种方式
    Java创建子类时构造器执行顺序
    转发&重定向
    Java继承
    GXOI&GZOI
    LCT能干啥???
    后缀自动机的一些应用
  • 原文地址:https://www.cnblogs.com/samsara-yx/p/13570057.html
Copyright © 2011-2022 走看看