gpt4 book ai didi

ios - 我将如何遍历所有键以获得特定的子值?

转载 作者:行者123 更新时间:2023-12-01 21:56:22 28 4
gpt4 key购买 nike

我正在尝试遍历“时间表”下的所有键,以获取具有"is"批准值的键值和名称。

所以对于下面的 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)
}
}
)

关于ios - 我将如何遍历所有键以获得特定的子值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61171125/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com