Created
September 4, 2014 17:08
-
-
Save dweinstein/debc10e13624cab4dcc1 to your computer and use it in GitHub Desktop.
walk a graph and generate an array of objects
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
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