Kudo
Kudo

Reputation: 51

ios firebase database get key of value

Sorry newbie here. I can't seem to find any solution that helps me get the following information from the firebase realtime database (see image)

orange rectangle marks structure of data and data to be retrieve

orange rectangle marks structure of data and data to be retrieve

This is my current code

ref.child("locations").observe(.value, with: { snapshot in
        for child in snapshot.children{
            let valueD = child as! DataSnapshot
            let keyD = valueD.key
            let value1 = valueD.value
            print(value1)
            // This gives "-L-other letters" = 0 (but I only want the string without "= 0")
}) 

Is there any way I can do this? Thanks!

Upvotes: 0

Views: 1763

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599041

If locations is the root of what you show in the screenshot, you're only looping over the first level of children (37d42... etc). To get the keys you marked, you need to loop one level deeper. So:

ref.child("locations").observe(.value, with: { snapshot in
    for child in snapshot.children{
        for grandchild in child.children{
            let valueD = grandchild as! DataSnapshot
            let keyD = valueD.key
            let value1 = valueD.value
            print(keyD)
        }
    }
}) 

Upvotes: 4

Related Questions