[英]flatMap a Dictionary of Dictionaries in Swift
我有一個NSEnumerator
,它包含如下嵌套的鍵值對象:
[ "posts" :
["randonRootKey1" :
["randomChildKey1" : [:] ]
],
["randonRootKey2" :
["randomChildKey2" : [:] ],
["randomChildKey3" : [:] ],
]
]
- posts
-- user1
--- posts
----post
-- user2
-- posts
--- post
我想將所有用戶的所有帖子提取到一個數組中...最后一個孩子和所有父母都是字典
我想flatMap它是:
[
["randomChildKey1" : [:] ],
["randomChildKey2" : [:] ],
["randomChildKey3" : [:] ]
]
請注意,我已經提取了每個根字典的對象。
我努力了 :
let sub = snapshot.children.flatMap({$0})
但似乎不起作用
let input: [String: [String: [String: Any]]] = ["posts":
[
"randonRootKey1": [
"randomChildKey1": [:],
],
"randonRootKey2": [
"randomChildKey2": [:],
"randomChildKey3": [:],
]
]
]
var output = [String: Any]()
for dictionary in input["posts"]!.values {
for (key, value) in dictionary {
output[key] = value
}
}
print(output)
[“ randomChildKey3”:[:],“ randomChildKey2”:[:],“ randomChildKey1”:[:]]
假設輸入采用這種格式
let input: [String: [String: [String: Any]]] = ["posts":
[
"randonRootKey1": [
"randomChildKey1": [:],
],
"randonRootKey2": [
"randomChildKey2": [:],
"randomChildKey3": [:],
]
]
]
使用這個
let output = input.flatMap{$0.1}.flatMap{$0.1}
您將獲得所需的輸出
[(“ randomChildKey1”,[:]),(“ randomChildKey2”,[:]),(“ randomChildKey3”,[:])]
如果要將元組轉換為字典,請使用reduce
let output = input.flatMap{$0.1}.flatMap{$0.1}.reduce([String: Any]())
{
(var dict, tuple) in
dict.append([tuple.0: tuple.1])
return dict
}
[[“” randomChildKey1“:{}],[” randomChildKey2“:{}],[” randomChildKey3“:{}]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.