Skip to content

Instantly share code, notes, and snippets.

@xnagpa
Created January 18, 2021 14:10
Show Gist options
  • Save xnagpa/a3466e76c6fa0deffbf489e8c30cb1c7 to your computer and use it in GitHub Desktop.
Save xnagpa/a3466e76c6fa0deffbf489e8c30cb1c7 to your computer and use it in GitHub Desktop.
Object tree traversal in vanilla javascript
// 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