Home > Software engineering >  Creating d3-hierachy using array of nodes and edges
Creating d3-hierachy using array of nodes and edges

Time:09-07

Stuck trying to create a tree using d3-hierachy, I have to use d3-heirachy since the library I am working with uses that structure. The API i'm working with returns a response as follows:

{
"Nodes": [
    {
        "Name": "node-1",
        "Type": "Model"
    },
    {
        "Name": "node-2",
        "Type": "Job"
    },
    {
        "Name": "node-3",
        "Type": "Data"
    },
    {
        "Name": "node-4",
        "Type": "Data"
    },
],
"Edges": [
    {
        "Source": "node-4",
        "Destination": "node-2"
    },
    {
        "Source": "node-3",
        "Destination": "node-2"
    },
    {
        "Source": "node-2",
        "Destination": "node-1"
    },
]}

And I'm trying to get an output as follows that can be used with d3-hierarchy:

[
 {
   Name: 'node-1',
   Type: 'Model',
   children: [
       {
         Name: 'node-2',
         Type: 'Job',
         children: [
             {
                 Name: 'node-3',
                 Type: 'Data'
             },
             {
                 Name: 'node-4',
                 Type: 'Data'
             },
         ]
       },
   ]
 }
]

Any help would be greatly appreciated!

CodePudding user response:

So first I group by Node names for easy access. Then I build the connections (as a parent child connection). That's it. I have the graph and all the possible entry points to it. I choose the first as it is hopefully the root of the tree.

var input={Nodes:[{Name:"node-1",Type:"Model"},{Name:"node-2",Type:"Job"},{Name:"node-3",Type:"Data"},{Name:"node-4",Type:"Data"},],Edges:[{Source:"node-4",Destination:"node-2"},{Source:"node-3",Destination:"node-2"},{Source:"node-2",Destination:"node-1"},]}

// first obj of nodes grouped by name
var obj_nodes = input.Nodes.reduce(function(agg, item) {
  agg[item.Name] = { ...item, children: [] };
  return agg;
}, {})
// console.log(obj_nodes)

// connecting edges (child parent relations)
input.Edges.forEach(function(item) {
  var source = obj_nodes[item.Source];
  var destination = obj_nodes[item.Destination];
  destination.children.push(source);
}, {})

var trees = Object.values(obj_nodes);

var result = trees[0]
console.log(result)
.as-console-wrapper {max-height: 100% !important}

  • Related