Home > front end >  How to efficiently build a tree from a tree structure
How to efficiently build a tree from a tree structure

Time:12-01

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 is like:

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

and I 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 one function recursive, this function is for restructure the tree.

code 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 built the new tree, its children are undefined, what I'm doing wrong?

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

CodePudding user response:

createTree() returns nothing, so assigning the return value to children would just make children have an undefined value.

One solution is to recursively call a helper method (e.g., named "createNode") that creates the tree nodes from each array element (instead of recursively calling createTree()). Return the result from 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

  • Related