我有一个NSEnumerator
,它包含嵌套的键值对象,如下所示:
[ "posts" :
["randonRootKey1" :
["randomChildKey1" : [:] ]
],
["randonRootKey2" :
["randomChildKey2" : [:] ],
["randomChildKey3" : [:] ],
]
]
- posts
-- user1
--- posts
----post
-- user2
-- posts
--- post
我想在一个数组中提取所有用户的所有帖子。。。最后一个孩子和所有父母都是字典
我想将其平面映射为:
[
["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",[,](,[("Random ChildKey3",[(]
如果要将元组转换为字典,请使用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":{