Created
January 15, 2019 10:18
-
-
Save Jei/a6506b6701dfa66aa2f6590ff3f8188f to your computer and use it in GitHub Desktop.
A simple method that reads a Map and returns a new map formatted as form data for https://pub.dartlang.org/packages/http
This file contains hidden or 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
Map<String, String> mapNested(Map<String, dynamic> obj, [Map<String, String> current, String namespace]) { | |
Map<String, String> res = current != null ? current : Map<String, String>(); | |
for (String key in obj.keys) { | |
String newKey = namespace != null ? '$namespace[$key]' : key; | |
if (obj[key] is Map) { | |
mapNested(obj[key], res, key); | |
} else if (obj[key] is List) { | |
for(int i = 0; i < obj[key].length; i++) { | |
mapNested(obj[key][i], res, "$key[$i]"); | |
} | |
} else { | |
res[newKey] = "${obj[key]}"; | |
} | |
} | |
return res; | |
} | |
// Example | |
print(mapToFormData({ | |
"foo": "bar", | |
"baz": [ | |
{ | |
"xyz": 123, | |
"wub": 456, | |
}, | |
{ | |
"xyz": 789, | |
"wub": 012, | |
}, | |
], | |
"wat": { | |
"rly": 0, | |
"ya": 1, | |
}, | |
})); | |
// should print | |
/* | |
{ | |
foo: bar, | |
baz[0][xyz]: 123, | |
baz[0][wub]: 456, | |
baz[1][xyz]: 789, | |
baz[1][wub]: 12, | |
wat[rly]: 0, | |
wat[ya]: 1 | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment