Skip to content

Instantly share code, notes, and snippets.

@obenjiro
Created January 14, 2015 16:53
Show Gist options
  • Select an option

  • Save obenjiro/4dd11806b270fb315365 to your computer and use it in GitHub Desktop.

Select an option

Save obenjiro/4dd11806b270fb315365 to your computer and use it in GitHub Desktop.
Tree to array
// 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