Search code examples
iosswiftfirebasefirebase-realtime-databasensdictionary

Get all keys exists in NSDictionary and put into Array


enter image description here

When I snapshot from child "abc" I got this NSDictionary, "3c" can be added more nested childs. How can I get all the keys within an NSDictionary and put into Array Expected result: ["abc","1a","2b","3c"]

value.allkeys just take same hierarchy keys


Solution

  • As @AechoLiu writes a recursive approach is a nice way to go about it. Something like the below:

    func nestedKeys(in dictionary: [String: Any]) -> [String] {
        guard let dictionaryValues = dictionary.values.filter({ $0 is [String: Any] }) as? [[String: Any]] else {
            return [String]() + dictionary.keys
        }
        let subKeys = dictionaryValues.reduce([String]()) { result, dictionary in
            return result + nestedKeys(in: dictionary)
        }
        return dictionary.keys + subKeys
    }
    

    The above expects your dictionaries to be of the format [String: Any] obviously.