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
}
}
Snapshots have two properties.
snapshot.key
snapshot.value
When using an observer with .value. all of the key: value children are returned in the snapshot. They can be iterated over to capture each key: value pair like this.
ref.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let value = snap.value
print("key = \(key) value = \(value!)")
}
})
Keep in mind that the value property could be a string, number, array or another dictionary (snapshot). In the original question it's a String.
Something like this should work (with better named variables):
snapshot.value
as a dictionary.keys
& .values
properties to retrieve them as LazyMapCollection
types.Code:
self.ref?
.child("data")
.child("success")
.child(userID!)
.observeSingleEvent(of: .value, with: { (snapshot) in
if let data = snapshot.value as? [String: Any] {
let keys = Array(data.keys)
let values = Array(data.values)
... // Your code here
}
}
Update - To show example where order is respected:
I would probably save the dictionary to an array, which casts it to type Array<(key: String, value: Any)>
. Then, you can map it to keys or values and keep the order.
... // As above
.observeSingleEvent(of: .value, with: { (snapshot) in
if let data = snapshot.value as? [String: Any] {
let dataArray = Array(data)
let keys = dataArray.map { $0.0 }
let values = dataArray.map { $0.1 }
... // Your code here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With