提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在项目中或多或少的会使用到树的样式,树形结构的数据的操作也会变的很重要
提示:以下是本篇文章正文内容,下面方法可供参考
一、获取第一个叶子节点的值
代码如下(示例):
getLeafValue(nodes) {
for (let i = 0; i < nodes.length; i++) {
if (!nodes[i].children||nodes[i].children.length === 0) {
return nodes[i];
} else {
if (nodes[i].children && nodes[i].children.length > 0) {
const leafValue = this.getLeafValue(nodes[i].children);
if (leafValue) {
return leafValue;
}
}
}
}
return null;
},
使用如下
var node=this.getLeafValue(this.treeData)
this.treeData是树形结构数据
二、遍历接口返回的数据,进行整合
代码如下(示例):
getChildData(data) {
let treeData = {};
const id = data.id;
const parentId = data.parentId;
const fullName = data.fullName;
const children = data.children;
treeData = {
fullName: fullName,
id: id,
disabled: true,
isLeaf: false,
type: 'project',
parentId: parentId,
children: [],
};
data.gridGroupList.forEach((item) => {
const leafOrigin = {
fullName: item.gridGroupName,
id: item.id,
disabled: false,
isLeaf: true,
type: 'group',
children: [],
};
treeData.children.push(leafOrigin);
});
if (children.length) {
this.getChildSonData(children, treeData);
}
this.searchTreeNodes.push(treeData);
},
getChildSonData(data, parentData) {
for (let i = 0; i < data.length; i++) {
const id = data[i].id;
const parentId = data[i].parentId;
const positionName = data[i].fullName;
const children = data[i].children ? data[i].children : [];
const node = {
fullName: positionName,
id: id,
parentId,
projectId: id,
disabled: true,
isLeaf: false,
type: 'project',
children: [],
noHasChildren: true,
};
data[i].gridGroupList.forEach((item) => {
const leafOrigin = {
fullName: item.gridGroupName,
id: item.id,
disabled: false,
isLeaf: true,
type: 'group',
children: [],
noHasChildren: true,
};
node.children.push(leafOrigin);
});
parentData.children.push(node);
if (children.length) {
this.getChildSonData(children, node);
}
}
return parentData;
},
//树形结构数据
let searchTreeNodes=[];
let treeData={
children:[{
fullName: "杭州市"
gridGroupList: [
areaId: "3301"
areaType: "行政区划"
configJson: null
geoJson: null
gridGroupName: "哈哈哈"
id: "586"
isActive: false
type: null
]
id: "3301"
latitude: 30.24603
longitude: 120.21079
parentId: "33"
type: 2
used: false
}]
fullName: "浙江省"
gridGroupList: []
id: "33"
latitude: null
longitude: null
parentId: "-1"
type: 1
used: false
}
//使用
this.getChildData(treeData)