Created
December 12, 2020 09:55
-
-
Save charlieInDen/a66f99b2ec19deff0789bf1738d99e5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///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