javascript - 如何使递归函数 vue.js 从孩子中获取数据
问题描述
我正在使用 vue.js 和 v-tree + vue2vis 网络,我有一棵树,里面有我所有的项目,比如这个:
items: [
{
id: 1,
name: 'root',
children: [
{
id: 2,
name: 'child1',
children: [
{
id: 3,
name: 'child3',
},
{
id: 4,
name: 'child34',
},
],
},
{
id: 5,
name: 'subroot',
children: [
{
id: 6,
name: 'Mike',
children:[
{
id: 7,
name: 'Mini Mike',
}
]
},
{
id: 8,
name: 'Hunt',
},
],
},
{
id: 9,
name: 'test',
children: [
{
id: 10,
name: 'Brandon',
},
{
id: 11,
name: 'Sean',
},
],
},
],
},
],
我想要做的是,当我点击树中的一个项目时,它会为网络生成数据,如下所示:
nodes: [{'id':1 , label: 'root'},{'id':2 , label: 'child1'},{'id':3 , label: 'child3'}]
and so on for all the children and parents
same goes for the edage i want to create conection between parent and child
edage: [{'from': 1, 'to':2},{'from': 2, 'to':3}]
我为这个想法尝试了这个功能,但它不起作用
makeNetConnection(items , itemKey) {
//items -> all the tree data
//itemKey-> its the item i click on the tree that i want to create the view
for (let item of items) {
if (item.name == itemKey) {
this.nodes.push({'id':item.id , 'label':item.name});
return item;
}
if (item.children) {
let i = this.makeNetConnection(item.children ,itemKey)
if (i) {
this.nodes.push({'id':item.id , 'label':item.name});
this.edges.push({'from': item.id , 'to': i.id});
return i;
}
}
}
它复制了数组中的数据,而不是与我希望拥有的父级连接,[{'from': 1, 'to':2},{'from': 2, 'to':3},{'from': 2, 'to':4}]
并且所有项目的操作系统都打开
但是我有[{'from': 1, 'to':2},{'from': 1, 'to':3} , {'from': 1, 'to':2},{'from': 1, 'to':3}, {'from': 1, 'to':4}, {'from': 1, 'to':4}]
我不知道 middel 连接如何使其工作?
解决方案
Maybe overkill, but use traverse
const traverse = require('traverse');
const returnData=[];
traverse.forEach(function(item){
returnData.push({id:item.id,label:item.value});
});
推荐阅读
- java - 无法下载 Android Studio Sdk
- javascript - 我将如何向我的网站添加 python 代码运行器
- r - 加快创建对象和应用功能的重复性任务
- javascript - Laravel + 反应
- java - 使用 Calimero for Java 读写 KNX 系统的有符号整数值
- android - 如何从新创建的自定义布局中删除背景
- python - Python os.system 和 mysqldump 的奇怪行为
- microsoft-graph-api - Microsoft Graph API - 503 服务不可用
- database - 单个端点和序列号是否会破坏 REST 的无状态性
- ruby-on-rails - Api::SessionsController#create 中的 NoMethodError