Created
January 14, 2015 16:53
-
-
Save obenjiro/4dd11806b270fb315365 to your computer and use it in GitHub Desktop.
Tree to array
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
| // parent links only | |
| function treeToArray(tree, parent){ | |
| if (!tree) return; | |
| tree.parent = parent; | |
| if (!tree.children) return [tree]; | |
| var children = tree.children; | |
| delete tree.children; | |
| if (!Array.isArray(children)) return [tree].concat([children]); | |
| return [].concat.apply([], [tree].concat(children.map(function(c){ return treeToArray(c, tree) }))) | |
| } | |
| //child links only | |
| function treeToArray(tree){ | |
| if (!tree) return; | |
| if (!tree.children) return [tree]; | |
| if (!Array.isArray(tree.children)) return [tree].concat([tree.children]); | |
| return [].concat.apply([], [tree].concat(tree.children.map(function(c){ return treeToArray(c) }))) | |
| } | |
| //child and parent links | |
| function treeToArray(tree, parent){ | |
| if (!tree) return; | |
| tree.parent = parent; | |
| if (!tree.children) return [tree]; | |
| if (!Array.isArray(tree.children)) return [tree].concat([tree.children]); | |
| return [].concat.apply([], [tree].concat(tree.children.map(function(c){ return treeToArray(c, tree) }))) | |
| } | |
| treeToArray({ a:1, children: [{ a:2, children: [{ a: 4 }, { a: 5 }] }, { a:3, children: { a: 6 } }] }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment