To solve this problem, we will utilize pure JavaScript without the need for any D3 method.
For reference, you can visit d3.hierarchy
...
The function constructs a main node based on the provided hierarchical data. The data given must be an object that represents the root node.
In essence, all that is required is to correctly specify the object.
For instance, if using the entire object (which may not be desired), it would look like this:
const data = {
"name": "A1",
"children": [
{
"name": "B1",
"children": [
{
"name": "B1-C1",
"value": 50
}
]
}
]
};
const root = d3.hierarchy(data);
console.log(root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Now, let's focus on extracting the specific object you desire. This can be achieved easily with the use of Array.prototype.find
:
const root = d3.hierarchy(data.children.find(d => d.name === "B1"));
Below is the code snippet demonstrating this concept:
const data = {
"name": "A1",
"children": [{
"name": "B1",
"children": [{
"name": "B1-C1",
"value": 50
}]
}]
};
const root = d3.hierarchy(data.children.find(d => d.name === "B1"));
console.log(root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>