export const filter = class Filter {
private data: Array<any>;
constructor(data: Array<any>) {
this.data = data;
}
public buildTree(): any[] {
const tree: any[] = [];
this.data.forEach((item) => {
if (!item.parentId) {
tree.push(this.createNode(item, this.data));
}
});
return tree;
}
private createNode(node: any, data: any[]): any {
const children: any[] = [];
data.forEach((item) => {
if (item.parentId === node.id) {
children.push(this.createNode(item, data));
}
});
if (children.length > 0) {
node.children = children;
}
return node;
}
public processData(): any[] {
const processedData = this.data.map((item) => {
return {
id: item.id,
name: item.name.toUpperCase(),
parentId: item.parentId,
};
});
return processedData;
}
}
----------------------------------------------
const data = [
{ id: 1, name: 'Root', parentId: null },
{ id: 2, name: 'Node 1', parentId: 1 },
{ id: 3, name: 'Node 2', parentId: 1 },
{ id: 4, name: 'Node 1.1', parentId: 2 },
{ id: 5, name: 'Node 1.2', parentId: 2 },
{ id: 6, name: 'Leaf', parentId: 4 },
];
const tree = new InitTree(data);
const builtTree = tree.buildTree();
const processedData = tree.processData();
console.log(builtTree);
console.log(processedData);
[
{
"id": 1,
"name": "Root",
"parentId": null,
"children": [
{
"id": 2,
"name": "Node 1",
"parentId": 1,
"children": [
{
"id": 4,
"name": "Node 1.1",
"parentId": 2,
"children": [
{
"id": 6,
"name": "Leaf",
"parentId": 4
}
]
},
{
"id": 5,
"name": "Node 1.2",
"parentId": 2
}
]
},
{
"id": 3,
"name": "Node 2",
"parentId": 1
}
]
}
]