【问题标题】:How do I loop through and get all the keys of the nested nodes in firebase?如何循环并获取firebase中嵌套节点的所有键?
【发布时间】:2016-06-03 04:56:56
【问题描述】:

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

例如在这种情况下:

example

我怎么知道 2,3,4 存在于 1 中?

我正在考虑将一个值单独放在 firebase 中的列表中。但是有没有更聪明的方法来做到这一点?有没有更有效的方法来获取 Firebase 中所有嵌套节点的键?

【问题讨论】:

  • 您在问题中包含了 JSON 树的图片。请将其替换为作为文本的实际 JSON,您可以通过单击 Firebase 数据库中的“导出”按钮轻松获取该文本。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,一般来说这只是一件好事。
  • 哎呀对不起,我是stackoverflow的新手。下次会做。感谢您的反馈!

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

在 Android 中

允许访问此快照的所有直接子项。可用于本机 for 循环:

for (DataSnapshot child : parent.getChildren()) { 
   //Here you can access the child.getKey()
}

在 iOS 中

斯威夫特 3:

for (child in snapshot.children) { 
  //Here you can access child.key
}

斯威夫特 4:

snapshot.children.forEach({ (child) in
  <#code#>
})

在网络中

snapshot.forEach(function(childSnapshot) {
   //Here you can access  childSnapshot.key
});

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

【讨论】:

    【解决方案2】:

    您需要使用字典数组。 遍历每个 Dictionary 然后您需要检查密钥是否存在。因为在 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)")
            }
        }
    

    目标-C

    NSString *key = @"1";
    for (NSDictionary *dic in array) {
        NSArray *keys = [dic allKeys];
        if ([keys containsObject:key]){
    
        }
    }
    

    【讨论】:

    • 问题标记为“swift”:请用 Swift 编写代码示例。谢谢。
    • 感谢您的编辑。 // The question also tagged as iOS 是的,还有? iOS 本身并不意味着 Objective-C,它只是意味着 iOS。要为 iOS 编写 代码,现在有 Objective-C 和 Swift,还有 Ruby 和 JavaScript……iOS 只是一个平台,它与一种特定的语言无关,当然也与 Objective-C 无关默认情况下。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-22
      • 2018-12-23
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多