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
createTree()
returns nothing, so assigning the return value tochildren
will only causechildren
to have anundefined
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 callingcreateTree()
). Return the result ofcreateTree()
and assign the return value todatatree
:Demo