Skip to content

Instantly share code, notes, and snippets.

@dweinstein
Created September 4, 2014 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dweinstein/debc10e13624cab4dcc1 to your computer and use it in GitHub Desktop.
Save dweinstein/debc10e13624cab4dcc1 to your computer and use it in GitHub Desktop.
walk a graph and generate an array of objects
function walk(obj) {
function root(key) {
return {key: key, text: key};
}
function node(parent, key, leaf) {
key = typeof key == 'number' ? String(key) : key;
parent = typeof parent == 'number' ? String(parent) : parent;
return {key: key, text: key, parent: parent, leaf: leaf};
}
function iter(parent, obj, accum) {
if (typeof obj == 'string') {
accum.push(node(parent, obj, true));
}
if (typeof obj == 'object') {
_.each(obj, function (val, key) {
accum.push(node(parent, key, false));
var children = iter(key, val, []);
accum = accum.concat(children);
});
}
return accum;
}
return iter('root', obj, [root('root')]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment