search

Home  >  Q&A  >  body text

How to efficiently build a tree from a tree structure

I have a bunch of objects in a tree structure. But currently this structure doesn't work for me because I need to use v-teeview so I need to restructure it...

My tree structure currently looks like this:

items: [
  {
    data: [
      { ... },
    ],
    children: [],
  },
  {
    data: [{ ... }],
    children: [{...}, {...}]
   }
] 

I need to restructure something like:

  items: [
      {     
         id: 76,
         name: "ADIS ",
         children: [],
      },
      {
        id: 64,
        name: "YSVERIS",
        children: [
          {
            id: 85,
            name: "MERCEDES",
            children: [],
          },
          {
            id: 83,
            name: "YNGRIBEL",  
            children: [],
          },
        ],
      }
    ]

So, I implemented a recursive function, which is used to reconstruct the tree.

Codes in codesandbox:

export default {
  methods: {
    createTree(items) {
      items.forEach((element) => {
        if (element.children.length === 0) {
          this.datatree.push({
            id: element.data[0].id,
            name: element.data[0].name,
            children: [],
          });
        } else {
          this.datatree.push({
            id: element.data[0].id,
            name: element.data[0].name,
            children: this.createTree(element.children),
          });
        }
      });
      console.log("root: ", this.datatree);
    },
  },
  mounted() {
    this.createTree(this.items);
  },
}

So my current problem is that when I build the new tree, its subtrees are undefined, what am I doing wrong?

In my example code, I use console.log() to see the new tree

P粉345302753P粉345302753312 days ago457

reply all(1)I'll reply

  • P粉401901266

    P粉4019012662024-03-29 12:33:48

    createTree() returns nothing, so assigning the return value to children will only cause children to have an undefined value.

    One solution is to recursively call a helper method (for example, named "createNode") that creates a tree node from each array element (instead of recursively calling createTree()). Return the result of createTree() and assign the return value to datatree:

    function createTree(items) {
      const createNode = ({ data, children }) => ({
        ...data[0],
        children: children?.map(child => createNode(child))
      })
      return items.map(item => createNode(item))
    }
    
    // MyComponent.vue
    export default {
      mounted() {
        this.datatree = createTree(this.items)
      }
    }
    

    Demo

    reply
    0
  • Cancelreply