Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new node to d3 tree

I've been having great success playing around with the d3 tree data structure using this example as a start:

http://bl.ocks.org/robschmuecker/7880033

However, there is one simple task that I cannot seem to find any answer to: add a node to the existing Data Tree. I am not trying to alter the original file where the data came from, nor do I just want to alter the svg output. I just want to be able to add a node directly to the Data Tree after it is rendered from an external file

like image 720
Nathan Avatar asked May 08 '26 14:05

Nathan


1 Answers

Its quite simple, Use this code to create a new node dynamically. Here selected is the node that has the current selection. It will be the parent of new node

const newNodeObj = {
    id: id,
    name: [],
    attributes: [],
    children: []
  };
    newNodeObj.name = '';
    newNodeObj.id = id;

  const newNode = d3.hierarchy(newNodeObj);
  newNode.depth = selected.depth + 1; 
  newNode.height = selected.height - 1;
  newNode.parent = selected;
  newNode.id = id;

    if (!selected.children) {
      selected.children = [];
      selected.data.children = [];
    }
    selected.children.push(newNode);
    selected.data.children.push(newNode.data);

 updateChart(this.selected);
like image 137
sa_n__u Avatar answered May 10 '26 04:05

sa_n__u



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!