2

I have been trying to find a way to print/isolate each of the children in a part of the JSON data structure in Firebase. I am using swift and another post mentioned and verified this as the solution.

for child in snapshot.childSnapshotForPath("vets").children {
    print(child.key)
}

but this is not valid because it comes with this warning.

Ambiguous use of 'key'

how do you recommend I loop through the data? All help is greatly appreciated.

AtulParmar
  • 4,358
  • 1
  • 24
  • 45
Ryan Cocuzzo
  • 3,109
  • 7
  • 35
  • 64

2 Answers2

4

Try this:

FIRDatabase.database().reference().child("vets").observeEventType(.Value, withBlock: { snapshot in
        if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
            for child in snapshots {
                print("Child: ", child)
            }
        }

    })
Meagan S.
  • 974
  • 9
  • 11
1

Just make an array of snapshot with keys and loop through it just like that if you want keys of "vets":

let ref = Database.database().reference().child("vets")

ref.observe(.childAdded) { (snapshot) in
    for key in [snapshot.key] {
        print(key)
    }
}

However, if you want the keys of "vets" children then you can do it like this:

ref.observe(.childAdded) { (snapshot) in
    guard let snapChildren = snapshot.value as? [String: Any] else { return }
    for (key, value) in snapChildren {
        print(key)
    }
}

If you need all key-value pairs of "vets" you may get them like this:

ref.observe(.childAdded) { (snapshot) in
    guard let snapChildren = snapshot.value as? [String: Any] else { return }
    for snap in snapChildren {
        print(snap)
    }
}

Wanna print value for a certain key of vets children? Let's say you want to print a vet name:

ref.observe(.childAdded) { (snapshot) in
    guard let snapChildren = snapshot.value as? [String: Any] else { return }
    for (key, value) in snapChildren {
        if key == "Name" {
            print(value)
        }
    }
}

Note: This code will work assuming your path is Database.database().reference().child("vets") and that each vet entry has some kind of AutoID or UID which is our snapshot.key in the first example.

ISS
  • 406
  • 6
  • 24