[英]Reduce an array of dictionary with many keys to an array of dictionary with a single key in Swift
我有一系列可以選擇的問題
[
{
"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
}
]
你可以用這樣的東西 map 你的陣列:
let secondArray: [[String : Int]] = array.compactMap { dict in
guard let id = dict["id"] as? Int else { return nil }
return ["question_id" : id]
}
但是用一個鍵返回字典有什么意義,而不僅僅是一個值數組......(?)
let questionIds = array.compactMap { dict in
return dict["id"]
}
您可以使用reduce
,然后在其閉包中獲取與鍵id
對應的值並將其存儲在鍵question_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)
enum Const: String {
case id = "id"
case questionId = "question_id"
}
let reduced = dict.reduce([]) {
guard let element = $1[Const.id.rawValue] else {
return $0
}
return $0 + [[Const.questionId.rawValue: element]]
}
或者您可以將其簡化為一個整數數組(僅適用於沒有任何“鍵”的商店 ID,因為它們在每個字典中都是相同的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.