Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda