如果后端返回的数据是树结构的对象形式
res.data.data.forEach(element => {
this.trreData.push({
title: element.apiModularClassify,
apiId: element.apiId,
children:
element.childrenClassify.length == 0
? ""
: element.childrenClassify.map(list => {
return {
title: list.apiFunctionClassify,
apiId: list.apiId,
children:
list.childrenApiServices.length == 0
? ""
: list.childrenApiServices.map(item => {
if (item.hasChild == "1") {
return {
title: item.apiFunctionClassify,
apiId: item.apiId,
children: []
};
} else {
return {
title: item.apiFunctionClassify,
apiId: list.apiId
};
}
})
};
})
});
});
如果后端返回的数据为对象形式
调用下面这个方法
this.trreData = util.getTree( //4.13 czy
this.examItemData,
'medtLinkClassId',
'className',
'parentId',
'全部', 0)[0].children
this.refectTreeDataAddOrclOneId(this.trreData);
util.getTree = function (soc, id, name,socs, pid, rootname, rootid) {
if (!rootid) rootid = 0;
// let resCopy = util.deepCopy(soc); // soc 复制一份,用于添加子节点使用
let hasChildren = true;
let nodeid = [];
let treeJson = {
title: rootname,
id: rootid,
data: {},
expand: true,
children: []
};
let nodeChildren = [];
soc.map((val, i) => { // 将所有的节点按照父节点id,生成一个 数组,元素为: {pid: 10, [{....},{....}]}
if (util.isEmpty(val[pid])) val[pid] = 0;
let pos = util.indexOfObject(val[pid], nodeChildren, 'pid');
if (pos >= 0) {
nodeChildren[pos].children.push(val);
} else {
nodeChildren.push({
'pid': val[pid],
'children': [val]
});
}
});
nodeid.push(rootid);
while (hasChildren) {
let newnodeid = [];
hasChildren = false;
nodeid.forEach((val, i) => {
let pos = util.indexOfObject(val, nodeChildren, 'pid');
if (pos >= 0) {
let pnode = util.treeMap(treeJson, val);
if (!util.isEmpty(pnode)) {
hasChildren = true;
nodeChildren[pos].children.forEach((node, j) => {
let newnode = {
title: node[name],
id: node[id],
pyCode: node.pyCode,
wbCode: node.wbCode,
data: node,
expand: true,
children: []
};
pnode.children.push(newnode);
newnodeid.push(node[id]);
});
}
}
});
nodeid = newnodeid;
}
let res = [treeJson];
return res;
};