Skip to main content

Command Palette

Search for a command to run...

inplement tree to list and list to tree with javascript

Published
•2 min read•View as Markdown

list to tree

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
   let tree = [
      { id: 1, parentId: null, name: 'a' },
      { id: 2, parentId: null, name: 'b' },
      { id: 3, parentId: 1, name: 'c' },
      { id: 4, parentId: 2, name: 'd' },
      { id: 5, parentId: 1, name: 'e' },
      { id: 6, parentId: 3, name: 'f' },
      { id: 7, parentId: 4, name: 'g' },
      { id: 8, parentId: 7, name: 'h' },
    ]

    const copy = JSON.parse(JSON.stringify(tree))

    // 双层遍历
    function listToTree(list){
      list.forEach(parent => {
        list.forEach(child => {
          if(parent.id === child.parentId) {
            if(!parent.children) {
              parent.children = []
            }
            parent.children.push(child)
          }
        })
      })
      list = list.filter(item => item.parentId === null)
      return list
    }
    const result = listToTree(copy)
    console.log(result);
    console.log(JSON.stringify(result));
    // [{"id":1,"parentId":null,"name":"a","children":[{"id":3,"parentId":1,"name":"c","children":[{"id":6,"parentId":3,"name":"f"}]},{"id":5,"parentId":1,"name":"e"}]},{"id":2,"parentId":null,"name":"b","children":[{"id":4,"parentId":2,"name":"d","children":[{"id":7,"parentId":4,"name":"g","children":[{"id":8,"parentId":7,"name":"h"}]}]}]}]
</script>
</body>
</html>

tree to list

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    const tree = [{ "id": 1, "parentId": null, "name": "a", "children": [{ "id": 3, "parentId": 1, "name": "c", "children": [{ "id": 6, "parentId": 3, "name": "f" }] }, { "id": 5, "parentId": 1, "name": "e" }] }, { "id": 2, "parentId": null, "name": "b", "children": [{ "id": 4, "parentId": 2, "name": "d", "children": [{ "id": 7, "parentId": 4, "name": "g", "children": [{ "id": 8, "parentId": 7, "name": "h" }] }] }] }]

    // 由外到内,深度优先
    function treeToArr(arr, result=[]) {
      for(let i = 0;i < arr.length; i++) {
        const obj = arr[i]
        const copy = JSON.parse(JSON.stringify(obj))
        delete obj.children
        result.push(obj)
        if(copy.children) {
          treeToArr(copy.children, result)
        }
      }
      return result
    }
    const arr = treeToArr(tree)
    console.log(JSON.stringify(arr)); 
    console.log(arr)
  </script>
</body>

</html>

More from this blog

EddieQiao's blog

84 posts

coder, work in suzhou