Created with <3 with dartpad.dev.
Created
January 23, 2024 13:30
-
-
Save Vamshi3130/d6dd551fc7f677c68614546870f84ec9 to your computer and use it in GitHub Desktop.
Key getter
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
void main() { | |
Map<String, dynamic> nestedMap = { | |
'key1': 'value1', | |
'key2': { | |
'key3': 'value3', | |
'key4': { | |
'key5': 'value5', | |
}, | |
}, | |
}; | |
List<String> allKeys = getAllKeys(nestedMap); | |
print('All keys in the nested map: $allKeys'); | |
} | |
List<String> getAllKeys(Map<String, dynamic> map) { | |
List<String> keys = []; | |
void traverse(Map<String, dynamic> currentMap, String currentPath) { | |
currentMap.forEach((key, value) { | |
String newPath = currentPath.isEmpty ? key : '$currentPath.$key'; | |
if (value is Map<String, dynamic>) { | |
keys.add(key); | |
traverse(value, newPath); | |
} else { | |
keys.add(key); | |
} | |
}); | |
} | |
traverse(map, ''); | |
return keys; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment