Last active
February 19, 2017 11:48
-
-
Save ilyaviache/24f8b62137a5d182b34c33e400a1103e to your computer and use it in GitHub Desktop.
Transform flat array into tree view. Wrapped in Angular2 pipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
@Pipe({ name: 'tree' }) | |
export class TreePipe implements PipeTransform { | |
transform(arr, args?: any[]) { | |
return this.buildTree(arr) | |
} | |
buildTree(elements, tree = []) { | |
elements.forEach((element) => { | |
if(!element.parent){ | |
element.children = this.getNestedChildren(elements, element._id) | |
tree.push(element) | |
} | |
}) | |
return tree; | |
} | |
getNestedChildren(elements, parent) { | |
let out = [] | |
elements.forEach((element) => { | |
if(element.parent == parent){ | |
let children = this.getNestedChildren(elements, element._id) | |
if(children.length > 0){ element.children = children; } | |
out.push(element) | |
} | |
}) | |
return out | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected input:
[ { id: 1 },{ id: 2 parent: 1 },{id: 3, parent: 1 }, {id: 4, parent: 2} ]