一维数组转树形结构

<!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>

posted @ 2020-08-27 10:42  Samsara315  阅读(932)  评论(0编辑  收藏  举报