JSFiddle - React, Tailwind, and code Playground

by ramnathv

JavaScript

var links = [
    {source: "A1", target: "A2"},
    {source: "A2", target: "A3"},
    {source: "A2", target: "A4"}
]

var nodesByName = {};

// Create nodes for each unique source and target.
links.forEach(function(link) {
    var parent = link.source = nodeByName(link.source),
        child = link.target = nodeByName(link.target);
    if (parent.children) parent.children.push(child);
    else parent.children = [child];
});

// Extract the root node.
var root = links[0].source;


function nodeByName(name) {
  return nodesByName[name] || (nodesByName[name] = {name: name});
}

console.log(JSON.stringify(links))