Skip to content
Advertisement

Count all sub child in firebase using React

i have, a data in firebase. the structure look like thisenter image description here

what i want is, to count all child inside a uid. so, i expect the values return 4enter image description here

i have tried like this

database.ref('data').on('value', (snap) => {
      console.log(snap.numChildren())
})

that return 2

how do i count all children in all uid?. so i can get 4

Advertisement

Answer

You can run a forEach loop on the snapshot and use numChildren() on all the child nodes.

database.ref('data').on('value', (snap) => {
  let total = 0
  snap.forEach(node => {
    console.log(node.val())
    total += node.numChildren()
  })

  console.log(total)
})
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement