0

This is more like an algorithmic question. I have two maps: depthMap and ChildMap. DepthMap is a javascript Map initiated with:

let depthMap = new Map()

After processing, I get following data inside the map:

0:[a,b,c,d]
1:[e,f]
2:[g,h,i]
3:[j]

Similarly, I have a childMap which I initialize like:

let childMap = new Map()

After processing, the childMap has following data:

a:[e,f]
b:[]
c:[]
d:[]
e:[g,h]
f:[i]
g:[]
h:[j]
i:[]
j:[]

Now I want to create a nested JSON object out of the depthMap and childMap. I need this dataset for the d3 indented tree. The final JSON should look something like this:

{
  name: 'a',
  children: [
     {
      name:e
      children: [
              {
                name: g,
                children:[]
              },
              {
                name: h,
                children: [..]
              }
           ]
     },
     {
       name: f
       children: [
          {
            name: i
            children: []
          }
       ]
     }
   ]
},
...

I am not exactly understanding how can I do this. I was thinking about using the trivial DFS algorithm to parse the graph considering the chilMap as an adjacency matrix.

However, I am not able to figure out how can I implement DFS to create such a JSON.

Any help will be appreciated. I would like to hear approaches using ES6/Javascript.

Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
Omkar
  • 2,274
  • 6
  • 21
  • 34

1 Answers1

2

I'd use a little recursion:

<!DOCTYPE html>
<html>

<body>
  <script>
  
    // base data
    var data = {
      'a': ['e', 'f'],
      'b': [],
      'c': [],
      'd': [],
      'e': ['g', 'h'],
      'f': ['i'],
      'g': [],
      'h': ['j'],
      'i': [],
      'j': []
    };
    
    // recursive funtion
    function iterV(v){
      
      return v.map( (k) => {
        
        var a = map.get(k); // get array
        map.delete(k); // remove from base map
        
        return {
          'name': k,
          'children': a ? iterV(a) : [] // recursively iterate
        };
      });
    }
    
    // kick it off
    var map = new Map(Object.entries(data)), // convert to map
        first = map.entries().next().value, // get first entry in map
        nest = {
          name: first[0],
          children: iterV(first[1]) // kick off recursion
        };
        
    console.log(nest);
    
  </script>
</body>

</html>
Mark
  • 106,305
  • 20
  • 172
  • 230
  • before even getting to this, I would like to thank you for your help and efforts. This has really solved my problem. Once again, many thanks Mark! – Omkar Mar 03 '18 at 15:37