Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created December 12, 2020 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieInDen/a66f99b2ec19deff0789bf1738d99e5f to your computer and use it in GitHub Desktop.
Save charlieInDen/a66f99b2ec19deff0789bf1738d99e5f to your computer and use it in GitHub Desktop.
///input - ["a": ["b": ["c": "1", "d": "1"]],
"e" : "1" ,
"f" : ["g": ["h": "1"]]]
///output - ["h": "1", "d": "1", "g": 1, "a": 3, "e": "1", "c": "1", "f": 2, "b": 2]
func flatten(dictionary: [String: Any]) -> [String: Any] {
func flattenRec(output: inout [String: Any], keyPath: String, value: Any, count: inout Int) {
let nCount = count
if value is String {
output[keyPath] = value
}
if let dict = value as? [String: Any] {
dict.forEach { key, value in
count = count + 1
flattenRec(output: &output, keyPath: key, value: value, count: &count)
}
output[keyPath] = count - nCount
}
}
var outputDict = [String: Any]()
dictionary1.forEach { key, value in
var count = 0
flattenRec(output: &outputDict, keyPath: key, value: value, count: &count)
}
return outputDict
}
//{ "a": { "b": { "c": 1, "d": 1 }, "e": 1, "f": { "g": { "h" : 1}}} }
let dictionary1 = ["a": ["b": ["c": "1", "d": "1"]],
"e" : "1" ,
"f" : ["g": ["h": "1"]]] as [String : Any]
let output = flatten(dictionary: dictionary1)
print(output)
//"["h": "1", "d": "1", "g": 1, "a": 3, "e": "1", "c": "1", "f": 2, "b": 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment