iOSGeek
iOSGeek

Reputation: 5577

flatMap a Dictionary of Dictionaries in Swift

I have an NSEnumerator which contains nested key value objects like this:

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

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

I want to extract all posts of all users in one array ... last child and all parents are dictionaries

I want to flatMap it to be :

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

Note that I have extracted the objects of each root dictionary.

I have tried :

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

but does not seem to work

Upvotes: 1

Views: 2352

Answers (2)

Ahmad Baracat
Ahmad Baracat

Reputation: 480

Assuming the input to be in this format

let input: [String: [String: [String: Any]]] = ["posts":
    [
        "randonRootKey1": [
            "randomChildKey1": [:],
        ],
        "randonRootKey2": [
            "randomChildKey2": [:],
            "randomChildKey3": [:],
        ]
    ]
]

Using this

let output = input.flatMap{$0.1}.flatMap{$0.1}

You will get the desired output

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

If you want to convert the tuple to dictionary use 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": {}]]

Upvotes: 1

Alexander
Alexander

Reputation: 63264

 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": [:]]

Upvotes: 1

Related Questions