如何解决Angular材质树形视图的数据处理
我正在尝试使用递归函数来处理数据,以使用角度材质树视图在树视图中显示数据。
我想转换为的数据格式:
export class TreeNode {
constructor(name,id,children = []) {
this.name = name;
this.id = id;
this.children = children;
}
name: string;
id: number;
children: TreeNode[] = []; depth can be maximum 5;
}
我拥有的数据的格式如下:
[{
description: "des",id: 43,childCenters: [{
description: "des",// this should be name of TreeNode
id: 1,// this should be id
childCenters[{
// and so on
}],consultants:[
name:"cname",// this should be name
id: 2 // this should be id
]
}],consultants:[
name:"cname",// this should be name
id: 2 // this should be id
]
}]
我用于转换的代码如下:
this.buildTreeNode(data); // data is raw data
buildTreeNode(list,isChildren = false) {
for(const currentNode of list) {
let newNode = new TreeNode(currentNode.description,currentNode.id,[])
if (currentNode.childCenters.length === 0) {
let arr = this.buildConsultantTreeNode(currentNode);
arr.forEach(data => {
newNode.children.push(data);
})
if (!isChildren) {
this.sampleDataSource.push(newNode);
} else {
return newNode;
}
} else {
currentNode.childCenters.forEach(childNode => {
let childTreeNode = new TreeNode(childNode.description,childNode.id,[]);
if (!(childNode.childCenters.length == 0)) {
const data = this.buildTreeNode(childNode.childCenters,true); // used recursion here.
childTreeNode.children.push(data);
}
let arr = this.buildConsultantTreeNode(childNode);
arr.forEach(data => {
childTreeNode.children.push(data);
})
newNode.children.push(childTreeNode);
});
let arr = this.buildConsultantTreeNode(currentNode);
arr.forEach(data => {
newNode.children.push(data);
})
}
if (!isChildren) {
this.sampleDataSource.push(newNode);
return newNode;
} else {
return newNode;
}
}
}
buildConsultantTreeNode(node) {
node.consultants.sort(function (a,b) {
if (a.name < b.name) { return -1; }
if (a.name > b.name) { return 1; }
return 0;
});
let arr: TreeNode[] = []
node.consultants.forEach(c => {
if (c.profitCenterId) {
c.parentProfitCenterId = c.profitCenterId;
}
const data = new TreeNode(c.name,c.id,[]);
arr.push(data);
});
return arr;
}
但是代码最多只能达到2个级别,任何帮助将不胜感激。 预先感谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。