Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda