Friday, 15 March 2013

Recursion - Converting Javascript Map into a nested JSON object -


Thanks in advance for help!

I am trying to change a specific JavaScript map, a sample of a nested JSON object map looks like this:

  ["a", ["b "" ["E", []] ["f", []]   / Pre> 

Where the key represents a parent node, and values ​​in the arrays are her direct children. For empty values, the empty array does not point to children for that key. I would like to generate one such output:

  {"name": "a", "children": [{"name "", "B", "children": ["name": "e"}}}, {"name": "c", "children": [{"name": "f",}]}]}}  

(This can not be a well-formed Jason object, but it is expected that there is an example of hierarchical relationships showing JavaScript example map). In addition, although trivial, however, the keys in the array and neither values ​​are considered to be solved.

Finally, I know that it lends itself to a recursive solution. Thanks again for any help would be highly appreciated!

The algorithm that you want to learn to solve this problem, assumes that in the graph described above There is no cycle, but in the case above the algorithm can only be modified to find nodes, which is not a parent to have a root node.

A possible solution:

  var is parent = {}; Function computeParentCount (data) {stack = []; (Key in data) {data [key] for ForEach (Work (Children) {Parents [Children] = True;}); }} Function appendAfterDfs (res, data, key) {var node = {name: key}; If (data [key] length) {// There are children in only nodes / / JSN nodes with children having more than 0 elements. Children = []; } Data [key] .for you (function (child) {appendoffer dfs (node ​​children, data, child);}); Res.push (node); } Function main () {var data = {'a': ['b', 'c'], 'b': ['e'], 'c': ['f'], 'e': [] , 'F': [],}; ComputeParentCount (data); // json var res = []; (Key in data) {if (!! [[Key]] {appendAfterDfs (res, data, key); }} Document.write ('& lt; Pre & gt;' + JSON.stringify (ridge, tap, '') + ';); Explanation:  
  1. Find the first key that is not a parent (and call it) root nodes)
  2. Every root node There is no child in a node until a dfs is executed by data object with
  3. submit each node in this process (this is done by parents' children Save in the array)

No comments:

Post a Comment