【问题标题】:flatMap a Dictionary of Dictionaries in SwiftflatMap Swift 中的字典字典
【发布时间】:2016-12-21 23:04:39
【问题描述】:

我有一个NSEnumerator,其中包含这样的嵌套键值对象:

 [ "posts" :
    ["randonRootKey1" :
        ["randomChildKey1" : [:] ]
    ], 
    ["randonRootKey2" :
        ["randomChildKey2" : [:] ],
        ["randomChildKey3" : [:] ],
    ]  
]

- posts
-- user1
--- posts
----post
-- user2
-- posts
--- post 

我想在一个数组中提取所有用户的所有帖子...最后一个孩子和所有父母都是字典

我想将它平面化为:

[
        ["randomChildKey1" : [:] ],
        ["randomChildKey2" : [:] ],
        ["randomChildKey3" : [:] ]
]

请注意,我已经提取了每个根字典的对象。

我试过了:

let sub = snapshot.children.flatMap({$0}) 

但似乎不起作用

【问题讨论】:

  • 你能给我们一个有效的快速语法输入和你想要的输出吗?
  • @AlexanderMomchliov 它只是一个带有随机键的字典,其中包含其他带有随机键的字典
  • 再次...您能否给我们一个有效的快速语法输入和您想要的输出?
  • 你有类似的东西:[["KOfgD9KrcCZYZB9JB5W"],["KOvJXpwckWfRs_IhguP"],[["-KNnRRu7Wv51bL_uvccp"],["-KNrlMKcNf1sZHzJvJrO"],["-KNrlf2e4PVegKgdupso"]]],对吗?所以:let flat = collections.flatMap { $0 } 将打印如下内容:["KOfgD9KrcCZYZB9JB5W", "KOvJXpwckWfRs_IhguP", ["-KNnRRu7Wv51bL_uvccp"], ["-KNrlMKcNf1sZHzJvJrO"], ["-KNrlf2e4PVegKgdupso"]]
  • @AlexanderMomchliov 查看更新后的问题

标签: ios swift flatmap


【解决方案1】:
 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": [:]]

【讨论】:

    【解决方案2】:

    假设输入是这种格式

    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": {}]]

    【讨论】:

    • 安全吗?发生了什么结构与第一个 flatMap 或第二个中的预期不同?
    • 不幸的是,它的输出是一个键/值元组数组,而不是字典。
    • @iOSGeek 你能举个例子说明你没有预期的结构是什么意思吗?
    • @AlexanderMomchliov 感谢您的提醒,我刚刚解决了这个问题。
    • @AhmedBaracat 如果 randonRootKey2 是一个空数组怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2018-01-05
    • 2015-05-10
    相关资源
    最近更新 更多