简体   繁体   English

如何从Firebase的键值对中获取键?

[英]how to get only key from key value pair in firebase ?

Trying to come up with some logic that could help in documenting few resources for firebase. 尝试提出一些逻辑,这些逻辑可以帮助记录很少的Firebase资源。 Have looked up few resources in regards to the problem, this question somewhat resembles the issue but not to the extend to solve it. 关于问题查找了很少的资源,这个问题有点像问题而不是扩展到解决它。 SimillarQuestion . SimillarQuestion And the avilable doc doesn't mention any logic to implement it either GoogleDoc . 可使用的文档或GoogleDoc都没有提及实现它的任何逻辑。

How to get only the keys from a given firebase json tree? 如何仅从给定的Firebase JSON树中获取密钥? As they say a pic tells thousand words. 当他们说图片时会说出千言万语。 Have got the below mentioned tree for firebase setup. 已获得以下提到的树用于Firebase设置。 And at mentioned is the required out put where it is displayed to the user in a table view. 并提到了必需的输出,在表格视图中将其显示给用户。

--uniUsers
      |
      |Fruits
      |   |
      |   |Apple:true
      |   |Kiwi:true
      |   |Orange:true
      | 
      |Veggies
          |
          |Carrot:true
          |Onions:true
          |Lettuce:true

Swift Code SWIFT代码

 func fetchTotalUsers(){
    let tempUniId = "Fruits"
    let refUniId = Database.database().reference(withPath: "UniUsers/\(tempUniId)")

refUniId.observe(.value, with: { (snapp) in

    print("Value><", snapp.key)
    print("Key><", snapp.value!)
   } 
     }

Swift OutPut: 迅捷输出:

  Value >< Fruits
  Key >< {
        Apple = 1;
        Kiwi = 1;
        Orange = 1;
        }

Required Output 所需输出

  Apple
  Kiwi 
  Orange

You can use keys property . 您可以使用keys属性。

From official documentation here 这里的官方文档

keys 按键

A collection containing just the keys of the dictionary. 仅包含字典键的集合。

Again from the official documentation: 再次从官方文档:

When iterated over, keys appear in this collection in the same order as they occur in the dictionary's key-value pairs. 迭代时,键在该集合中的显示顺序与在字典的键/值对中出现的顺序相同。 Each key in the keys collection has a unique value. 键集合中的每个键都有一个唯一的值。

So in your particular case you can do some thing like this: 因此,在您的特定情况下,您可以执行以下操作:

Since you get dictionary from the firebase server 由于您是从Firebase服务器获取字典的

refUniId.observe(.value, with: { (snapp) in

    print("Value><", snapp.key)
    print("Key><", snapp.value!)

    if let dict = snapp.value as? [String: Any] {

        for k in dict.keys {
             print(k)
        }
    } 
}

Found by using enumeration we can go step by step but for a newbie the answer selected makes more sense in terms of readability unless the concept of enumeration is known before 通过使用枚举发现,我们可以逐步进行,但是对于新手来说,除非可读性高,否则选择的答案在可读性方面更有意义。

 refUniId.observe(.value, with: { (snapp) in

     print("Count><", snapp.childrenCount)

    let enumeratorRR = snapp.children
    while let rest = enumeratorRR.nextObject() as? DataSnapshot{
    print("GotRequiredFruits",rest.key)
    }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM