如何遍历并获取 firebase 中嵌套节点的所有键?

How do I loop through and get all the keys of the nested nodes in firebase?

我正在尝试获取 Firebase 中嵌套节点的键,但我不确定如何执行此操作。

例如在这种情况下:

example

我怎么知道 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
});

您可以将它放在不同的列表或相同的路径中,重要的是要记住在调用事件时您真正检索了多少数据。以及您将如何查询该信息...这就是为什么在 NoSQL 中建议保持扁平节点

您需要使用字典数组。 遍历每个 Dictionary 然后您需要检查密钥是否存在。因为在 Firebase 中我们需要将特定的密钥发送到服务器。

SWIFT

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]){

    }
}

我找到了一种迭代嵌套 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("-")
        }