I have a list of edge lists that construct a tree:
[
    {'start': 'A', 'end': 'B'},
    {'start': 'B', 'end': 'C'},
    {'start': 'B', 'end': 'D'},
    {'start': 'D', 'end': 'E'},
    {'start': 'D', 'end': 'F'},
    {'start': 'D', 'end': 'G'},
]
And I use a recursive function to turn the data into a nested from:
{
    'name': 'A',
    'children': [
        {
            'name': 'B',
            'children': [
                {
                    'name': 'C',
                    'children': []
                },
                {
                    'name': 'D',
                    'children': [
                        {
                            'name': 'E',
                            'children': []
                        },
                        {
                            'name': 'F',
                            'children': []
                        },
                        {
                            'name': 'G',
                            'children': []
                        },
                    ]
                }
            ]
        }
    ]
}
I want to ask if d3js already has something built-in that would achieve the same result ?
Try d3.stratifyᵈᵒᶜˢ, it takes a list of parent child relationships and creates a hierarchy that can be passed to d3.tree or whatever else.
With your data array, containing objects with properties start (parent) and end (child), you could use:
  var root = d3.stratify()
    .id(function(d) { return d.end; })
    .parentId(function(d) { return d.start; })(dataArray)
One thing to note, you need an item that has no parent, this will become the root: "For the root node, the parent id should be undefined. (Null and the empty string are equivalent to undefined)" ᵈᵒᶜˢ. So in your case, we would still need to add an item to your data array: {'start': '', 'end': 'A'}.
var data = [
    {'start': '', 'end': 'A'},
    {'start': 'A', 'end': 'B'},
    {'start': 'B', 'end': 'C'},
    {'start': 'B', 'end': 'D'},
    {'start': 'D', 'end': 'E'},
    {'start': 'D', 'end': 'F'},
    {'start': 'D', 'end': 'G'},
]
var root = d3.stratify()
    .id(function(d) { return d.end; })
    .parentId(function(d) { return d.start; })
    (data);
    
console.log(root);<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>The snippet's console is poor in this case, use the browser console to view the returned hierarchy properly. The returned data structure is the same as in your question, but with added properties for things like node depth, node data, etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With