Created
May 15, 2025 08:06
-
-
Save BekNaji/bb8a19d104f22369cf097d06c706db6f to your computer and use it in GitHub Desktop.
set deep map in dart
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
void main() async { | |
Map<String, dynamic> setDeep( | |
Map<String, dynamic> data, { | |
required String path, | |
required dynamic value, | |
String separator = '.', | |
}) { | |
final keys = path.split(separator); | |
Map<String, dynamic> current = data; | |
for (int i = 0; i < keys.length; i++) { | |
final key = keys[i]; | |
if (i == keys.length - 1) { | |
current[key] = value; | |
} else { | |
if (current[key] == null || current[key] is! Map) { | |
current[key] = <String, dynamic>{}; | |
} | |
current = current[key] as Map<String, dynamic>; | |
} | |
} | |
return data; | |
} | |
try { | |
Map<String, dynamic> data = {"name": "Bekzod"}; | |
data['phone'] = "+998946153095"; | |
setDeep(data, path: 'file.some.field.value', value: 'file name'); | |
print(data); | |
} catch (e) { | |
print('error'); | |
print(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment