• 一维数组转树形结构


    <!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>
    
    
  • 相关阅读:
    暑假日报-11
    暑假日报-10
    暑假日报-9
    暑假日报-8
    暑假日报-7
    暑假日报-6
    暑假日报-5
    暑假日报-4
    暑假日报-3
    第二次集训的每日感想
  • 原文地址:https://www.cnblogs.com/samsara-yx/p/13570057.html
Copyright © 2020-2023  润新知