我有一个NSEnumerator,它包含嵌套的键值对象,如下所示:
[ "posts" :
["randonRootKey1" :
["randomChildKey1" : [:] ]
],
["randonRootKey2" :
["randomChildKey2" : [:] ],
["randomChildKey3" : [:] ],
]
]
- posts
-- user1
--- posts
----post
-- user2
-- posts
--- post 我想在一个数组中提取所有用户的所有帖子.最后一个孩子和所有的父母都是字典
我想flatMap它是:
[
["randomChildKey1" : [:] ],
["randomChildKey2" : [:] ],
["randomChildKey3" : [:] ]
]注意,我已经提取了每个根字典的对象。
我试过:
let sub = snapshot.children.flatMap({$0}) 但似乎不起作用
发布于 2016-08-15 18:33:24
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":]
发布于 2016-08-15 19:15:06
假设输入为此格式
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":{}]
https://stackoverflow.com/questions/38960210
复制相似问题