Firebase - retrieve all child keys and child values into separate arrays in Swift

Viewed 14255

Is there any way to retrieve all the keys in a child, put them into array, and then retrieve the values for the keys and put it into another array?

Source code:

self.ref?.child("data").child("success").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
   if snapshot != nil {
        // Your answer goes here
   }
}
4 Answers

If you prefer mapping instead of iteration like me, you can do

let keys = snapshot.children.compactMap { ($0 as? DataSnapshot)?.key }
let values = snapshot.children.compactMap { ($0 as? DataSnapshot)?.value }
Related