Last active
November 8, 2020 23:54
-
-
Save jorwan/52902870f633da8959a39353e96fac25 to your computer and use it in GitHub Desktop.
Remove property with null values and null values from list
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
/* | |
* Goal: Remove property with null values and null values from list | |
* Author: Jorge Wander Santana Urena | |
* Source: https://gist.github.com/jorwan/52902870f633da8959a39353e96fac25 | |
**/ | |
final data = | |
{ | |
"name": "Carolina Ratliff", | |
"company": null, | |
"phone": "+1 (919) 488-2302", | |
"tags": [ | |
"commodo", | |
null, | |
"dolore", | |
], | |
"friends": [ | |
{ | |
"id": 0, | |
"name": null, | |
"favorite_fruits": [ | |
'apple', null, null, 'pear' | |
] | |
}, | |
{ | |
"id": 1, | |
"name": "Pearl Calhoun" | |
}, | |
], | |
}; | |
void main() { | |
// From map | |
print('Remove nulls from map:\n' + data.removeNulls().toString()); | |
// From list | |
print('\nRemove nulls from list:\n' + [data].removeNulls().toString()); | |
} | |
Map<String, dynamic> removeNullsFromMap(Map<String, dynamic> json) => | |
json | |
..removeWhere((String key, dynamic value) => value == null) | |
..map<String, dynamic>((key, value) => MapEntry(key, removeNulls(value))); | |
List removeNullsFromList(List list) => list | |
..removeWhere((value) => value == null) | |
..map((e) => removeNulls(e)).toList(); | |
removeNulls(e) => (e is List) | |
? removeNullsFromList(e) | |
: (e is Map ? removeNullsFromMap(e) : e); | |
extension ListExtension on List { | |
List removeNulls() => removeNullsFromList(this); | |
} | |
extension MapExtension on Map { | |
Map removeNulls() => removeNullsFromMap(this); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment