Created
January 18, 2021 14:10
-
-
Save xnagpa/a3466e76c6fa0deffbf489e8c30cb1c7 to your computer and use it in GitHub Desktop.
Object tree traversal in vanilla javascript
This file contains 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
// Usage example: | |
forEachTreeNode(tree, (node) => { | |
console.log(node.title); | |
}); | |
// Implementation | |
const forEachTreeNode = (obj, func): void => { | |
if (!obj) return; | |
func(obj); | |
if (obj.children && obj.children.length > 0) { | |
obj.children.forEach((x) => forEachTreeNode(x, func)); | |
} | |
}; | |
// Acceptable Tree structure: | |
const tree = { title: 'Main node!', children: [ | |
{ title: 'node 1' }, | |
{ title: 'node 2', children: [ | |
{ title: 'node 2.1' }, | |
{ title: 'node 2.2', children: [ | |
{ title: 'node 2.2.1' }, | |
{ title: 'node 2.2.2' }, | |
{ title: 'node 2.2.3' }, | |
] }, | |
{ title: 'node 2.3' }, | |
] }, | |
{ title: 'node 3' }, | |
]}; | |
// Output of "forEachTreeNode(tree, (node) => console.log(node.title));" | |
// Main node! | |
// node 1 | |
// node 2 | |
// node 2.1 | |
// node 2.2 | |
// node 2.2.1 | |
// node 2.2.2 | |
// node 2.2.3 | |
// node 2.3 | |
// node 3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment