我试图遍历“时间表”下的所有键,以获取键值和具有“是”的批准值的名称。

因此,对于以下JSON结构:

Timetable

   Pikes_Lane_Primary_School_Bolton_UK
      Approved: Yes
      Name: Pikes Lane Primary School

   Essa_Academy_Bolton_UK
      Approved: No
      Name: Essa Academy

   Ladybridge_High_School_Bolton_UK
      Approved: Yes
      Name: Ladybridge High School

我想要的输出将是:
Pikes_Lane_Primary_School_Bolton_UK
Pikes Lane Primary School
Ladybridge_High_School_Bolton_UK
Ladybridge High School

这是我在过去几个小时内努力做到的最好的事情:
        let schoolDatabase = Database.database().reference().child("Timetable")
        schoolDatabase.observeSingleEvent(of: .value, with: { (snapshot) in
            for child in snapshot.children {
                let schoolID = child as! DataSnapshot
                //print(schoolID.key)
                for grandchild in schoolID.children {
                    let varOne = grandchild as! DataSnapshot
                    print(varOne.key)
                }
            }
        })

这带来了以下内容:
Approved
Name
Approved
Name
Approved
Name

最佳答案

    let schoolDatabase = Database.database().reference().child("Timetable")
    schoolDatabase
        .queryOrdered(byChild: "Approved")
        .queryEqual(toValue: "Yes")
        .observeSingleEvent(of: .value, with: { (snapshot) in
            let children = snapshot.children
                .compactMap { $0 as? DataSnapshot }

            children.forEach { tuple in
                print(tuple.key)

                if let tupleDictionary = tuple.value as? [String: Any] {
                    let name = tupleDictionary["Name"] as? String
                    print(name ?? "-")
                }
            }
        }
    )

或者,如果您仅对名称感兴趣(不带键):
    let schoolDatabase = Database.database().reference().child("Timetable")
    schoolDatabase
        .queryOrdered(byChild: "Approved")
        .queryEqual(toValue: "Yes")
        .observeSingleEvent(of: .value, with: { (snapshot) in
            let children = snapshot.children
                .compactMap { $0 as? DataSnapshot }
                .compactMap { $0?.value as? [String: Any]}
                .compactMap { $0["Name"] as? String }


            children.forEach { name in
                print(name)
            }
        }
    )

07-24 09:33