Skip to content

Instantly share code, notes, and snippets.

@jorwan
Last active November 8, 2020 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorwan/52902870f633da8959a39353e96fac25 to your computer and use it in GitHub Desktop.
Save jorwan/52902870f633da8959a39353e96fac25 to your computer and use it in GitHub Desktop.
Remove property with null values and null values from list
/*
* 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