Arrays 如何从字典数组中检索具有相同名称的所有键的值
我想从字典数组中的所有字典中检索名为termKey的键的值,因为我想在UITableView中显示这些值。有什么建议吗 以下是字典数组:Arrays 如何从字典数组中检索具有相同名称的所有键的值,arrays,swift,dictionary,Arrays,Swift,Dictionary,我想从字典数组中的所有字典中检索名为termKey的键的值,因为我想在UITableView中显示这些值。有什么建议吗 以下是字典数组: { "questionData": [ { "termKey": "respiration" }, { "termKey": "mammals" } ] } 这是展平阵列: [(key: "termKey", value: "respiration"), (key: "termKey", val
{
"questionData": [
{
"termKey": "respiration"
},
{
"termKey": "mammals"
}
]
}
这是展平阵列:
[(key: "termKey", value: "respiration"), (key: "termKey", value: "mammals")]
我想要的输出是:[呼吸,哺乳动物]
您将得到一个值数组,如下所示:
["respiration", "mammals"]
在数组上使用,并在闭包中查找字典键:
let questionData = [["termKey": "respiration"], ["termKey": "mammals"], ["badKey": "foo"]]
let values = questionData.compactMap { $0["termKey"] }
print(values)
compactMap为数组中的每个元素运行闭包以创建新数组。在这里,我们查找key termKey的值。字典查找返回一个可选值。如果密钥不存在,结果将为零。compactMap跳过nil值并打开存在的值。将JSON解码为结构并将结果映射到questionData的termKey值
let questionData = [["termKey": "respiration"], ["termKey": "mammals"], ["badKey": "foo"]]
let values = questionData.compactMap { $0["termKey"] }
print(values)
["respiration", "mammals"]
struct Response: Decodable {
let questionData : [Question]
}
struct Question: Decodable {
let termKey : String
}
let jsonString = """
{"questionData": [{"termKey": "respiration"},{"termKey": "mammals"}]}
"""
let data = Data(jsonString.utf8)
do {
let result = try JSONDecoder().decode(Response.self, from: data)
let termKeys = result.questionData.map{$0.termKey}
} catch { print(error) }