如何循环访问并获取Firebase中所有嵌套节点的密钥?
我正在尝试获取Firebase中的嵌套节点的密钥,我不知道如何执行此操作。
例如在这种情况下:
例
我怎么知道2,3,4在1之内?
我正在考虑在firebase中单独列出一个值。 但有没有更聪明的方法呢? 是否有更有效的方式获取Firebase中所有嵌套节点的键?
在Android中
可以访问此快照的所有直接子项。 可以在本地for循环中使用:
for (DataSnapshot child : parent.getChildren()) { //Here you can access the child.getKey() }
在iOS中
Swift 3:
for (child in snapshot.children) { //Here you can access child.key }
Swift 4:
snapshot.children.forEach({ (child) in <#code#> })
在网上
snapshot.forEach(function(childSnapshot) { //Here you can access childSnapshot.key });
你可以把它放在不同的列表中,或者放在同一个path中,重要的是要记住在调用一个事件时你真正检索了多less数据。 你将如何查询这些信息……这就是为什么在NoSQL中推荐保持扁平节点的原因
你需要使用字典数组。 迭代每个字典,然后你需要检查密钥是否存在或不。 因为在Firebase中,我们需要将特定的密钥发送到服务器。
迅速
let key = "1" for child in snapshot.children { if let snap = child.childSnapshotForPath(key){ print("Able retrieve value : \(snap) for key : \(key)") } else { print("Unable to retrieve value for key : \(key)") } }
Objective-C的
NSString *key = @"1"; for (NSDictionary *dic in array) { NSArray *keys = [dic allKeys]; if ([keys containsObject:key]){ } }
我find了一种方法来迭代嵌套的JSON,其键是随机的。
var ref = FIRDatabase.database().reference(withPath: "timinig") ref.observeSingleEvent(of: .value, with: { snapshot in print(snapshot.childrenCount) // I got the expected number of items let enumerator = snapshot.children while let rest = enumerator.nextObject() as? FIRDataSnapshot { print("-") print(rest.key) let newobj=rest.children while let rest1 = newobj.nextObject() as? FIRDataSnapshot { print(rest1.key) } print("-") }