我有一堆树结构中的对象。但目前这个结构对我来说不起作用,因为我需要使用v-teeview,所以我需要重新构造它......
我的树结构目前是这样的:
items: [
{
data: [
{ ... },
],
children: [],
},
{
data: [{ ... }],
children: [{...}, {...}]
}
]
我需要重组类似的东西:
items: [
{
id: 76,
name: "ADIS ",
children: [],
},
{
id: 64,
name: "YSVERIS",
children: [
{
id: 85,
name: "MERCEDES",
children: [],
},
{
id: 83,
name: "YNGRIBEL",
children: [],
},
],
}
]
所以,我实现了一个递归函数,这个函数是为了重构树。
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);
},
}
所以我当前的问题是,当我构建新树时,它的子树未定义,我做错了什么?
在我的示例代码中,我使用 console.log() 来查看新树
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号