Recursion - Converting Javascript Map into a nested JSON object -
thank in advance help!
i'm attempting convert specific javascript map nested json object. sample of map looks like:
["a", ["b", "c"]] ["b", ["e"]] ["c", ["f"]] ["e", []] ["f", []]
where key represents parent node, , values in arrays direct children. empty arrays values indicates no children given key. generate output looks like:
{ "name": “a”, "children": [{ "name": “b”, "children": [{ "name": “e” }] }, { "name": “c”, "children": [{ "name": “f”, }] }] }
(this may not well-formed json object typed, illustrative of hierarchical relationship javascript example map demonstrating). additionally, though trivial, keys nor values in arrays assumed sorted.
lastly, know lends recursive solution. immensely appreciated. thank again time!
the algorithm want learn solve problem called topological sorting, assumes graph have described above doesn't have cycle, case above algorithm can modified little bit find nodes have no parent root nodes.
a possible solution:
var hasparent = {}; function computeparentcount(data) { stack = []; (key in data) { data[key].foreach(function (child) { hasparent[child] = true; }); } } function appendafterdfs(res, data, key) { var node = { name: key }; if (data[key].length) { // nodes children array more 0 elements // have children in json node.children = []; } data[key].foreach(function (child) { appendafterdfs(node.children, data, child); }); res.push(node); } function main() { var data = { 'a': ['b', 'c'], 'b': ['e'], 'c': ['f'], 'e': [], 'f': [], }; computeparentcount(data); // build json var res = []; (key in data) { if (!hasparent[key]) { appendafterdfs(res, data, key); } } document.write('<pre>' + json.stringify(res, null, ' ') + '</pre>'); } main()
explanation:
- first find keys have no parent (and call them
root
nodes) - with each root node perform dfs through
data
object until node doesn't have children - collect each node in process (saving in parent's children array)
Comments
Post a Comment