Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Javascript / D3 - text to display only count of children

I have a static force node visual that looks like this:

enter image description here

And relevant code:

 const node2 = g.append("g")
.selectAll(".labels")
.data(nodes)
.join("text")
.attr('x', d=> d.x)
.attr('y', d=> d.y+3)
.attr('text-anchor','middle')
.attr('class','labels')
//.text(d=> d.data.name)
.text(function(d,i) {return i-2})
.style("fill", d=> d.children ? "none": d.data.new==true?"#fff":"#000")
.style('font-size',12);

Data looks like:

{"name":"Name1", tree: {
"name":"center",
"children": [
    {"name":"category1","children":[{"name":"node1"},{"name":"node2"},{"name":"node3"}]},
    {"name":"category2","children":[{"name":"node4"},{"name":"node5"}]},
]
}
}

What I would like to have here is for the labels to display a count sort of "id" for each node starting from 1. I initially thought I could subtract off 2 like: i-2. However for simpler force structures this resulted in too much, leaving the count starting at 0.

Question

How can I make my count logic robust to display a count that includes only children (regardless of parent/overall structure)

Edit

I've also tried to apply a parent count logic, but this gave me all NaNs:

.text(function(d,i) {
  if (d.depth==0) {
    console.log(d)
    var parents = d.children.length;
  }
  return i-parents;
  //return i-2
})

Edit 2 I got it working by changing parents to a global but it seems a bit hacky. Still would welcome a more sophisticated answer.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!