Ios 在Swift中将具有多个键的字典数组减少为具有单个键的字典数组
我有一系列可以选择的问题Ios 在Swift中将具有多个键的字典数组减少为具有单个键的字典数组,ios,arrays,swift,dictionary,Ios,Arrays,Swift,Dictionary,我有一系列可以选择的问题 [ { "id": 1, "title": "test", "info": "Test123", "is_selected": true }, { "id": 2, "title": "test2", "info": "test2", "is_selected": false }, { "id": 3, "title": "test23", "info": "te
[
{
"id": 1,
"title": "test",
"info": "Test123",
"is_selected": true
},
{
"id": 2,
"title": "test2",
"info": "test2",
"is_selected": false
},
{
"id": 3,
"title": "test23",
"info": "test23",
"is_selected": true
}
]
如何将这个包含多个键的字典数组简化为包含单个键的字典数组
[
{
"question_id": 1
},
{
"question_id": 2
}
]
您可以使用
reduce
,然后在其闭包中获取与键id
对应的值,并将其存储在键question\u id
下的新词典中
let dictionariesWithSingleKey = dictionariesWithManyKeys.reduce(into: [[String:Int]](), { result, current in
guard let questionId = current["id"] as? Int else { return }
let singleKeyedDict = ["question_id": questionId]
result.append(singleKeyedDict)
})
print(dictionariesWithSingleKey)
您可以使用
reduce
,然后在其闭包中获取与键id
对应的值,并将其存储在键question\u id
下的新词典中
let dictionariesWithSingleKey = dictionariesWithManyKeys.reduce(into: [[String:Int]](), { result, current in
guard let questionId = current["id"] as? Int else { return }
let singleKeyedDict = ["question_id": questionId]
result.append(singleKeyedDict)
})
print(dictionariesWithSingleKey)
您可以使用以下内容映射阵列:
let secondArray: [[String : Int]] = array.compactMap { dict in
guard let id = dict["id"] as? Int else { return nil }
return ["question_id" : id]
}
但是,用一个键而不仅仅是一个值数组返回dicts有什么意义…(?)
您可以使用以下内容映射阵列:
let secondArray: [[String : Int]] = array.compactMap { dict in
guard let id = dict["id"] as? Int else { return nil }
return ["question_id" : id]
}
但是,用一个键而不仅仅是一个值数组返回dicts有什么意义…(?)
或者,您可以将其简化为一个整数数组(仅适用于没有任何“键”的存储ID,因为它们在每个字典中都是相同的)
或者,您可以将其简化为一个整数数组(只针对没有任何“键”的存储id,因为它们在每个字典中都是相同的)api需要[[“问题id”:4],“问题id”:5],“问题id”:8]]作为所选问题的参数。api需要[[“问题id”:4],“问题id”:5],“问题id”:8]]将所选问题作为参数。