I have two lists of maps in flutter:
List<Map<String, dynamic>> cities = [
{'id':1, 'name':'City A', 'city_code':'CA' },
{'id':2, 'name':'City B', 'city_code':'CB' },
{'id':3, 'name':'City C', 'city_code':'CC' },
{'id':4, 'name':'City D', 'city_code':'CD' },
{'id':5, 'name':'City E', 'city_code':'CE' },
];
List<Map<String, dynamic>> populationData = [
{'id':1, 'city_code':'CA', 'year': 2018, 'population': 111111},
{'id':2, 'city_code':'CA', 'year': 2019, 'population': 222222},
{'id':3, 'city_code':'CA', 'year': 2020, 'population': 333333},
{'id':4, 'city_code':'CE', 'year': 2018, 'population': 444444},
{'id':5, 'city_code':'CB', 'year': 2021, 'population': 555555},
{'id':6, 'city_code':'CB', 'year': 2017, 'population': 666666},
{'id':7, 'city_code':'CD', 'year': 2019, 'population': 777777},
{'id':8, 'city_code':'CD', 'year': 2020, 'population': 888888},
];
I want to group the population data based on city_code
and embed it into the cities
map list. In other words, i just want to combine the two map lists into one (or merge the second one into first one based on city_code) like this:
List<Map<String, dynamic>> cities = [
{'id':1, 'name':'City A', 'city_code':'CA', 'population_data': [{'year': 2018, 'population': 111111},{'year': 2019, 'population': 222222}] },
{'id':2, 'name':'City B', 'city_code':'CB', 'population_data': [{'year': 2021, 'population': 555555},{'year': 2017, 'population': 666666}] },
{'id':3, 'name':'City C', 'city_code':'CC', 'population_data': [] },
{'id':4, 'name':'City D', 'city_code':'CD', 'population_data': [{'year': 2019, 'population': 777777},{'year': 2020, 'population': 888888}] },
{'id':5, 'name':'City E', 'city_code':'CE', 'population_data': [{'year': 2018, 'population': 444444}] },
];
I don't know how to do it in flutter. Can someone please show how to do it?
CodePudding user response:
You can concatenate 2 different lists with any condition using .map() and .where() functions of the List class. Here is the simple solution, for the example that you have provided
List<Map<String, dynamic>> result = cities.map((cityData) => {
'id': cityData['id'],
'name': cityData['name'],
'city_code': cityData['city_code'],
'population_data': populationData
.where((popData) => popData['city_code'] == 'CA')
.toList()
.map((popData) => {'year': popData['year']})
.toList()
}).toList();
CodePudding user response:
You can do this:
for (var item in cities) {
item.putIfAbsent(
'population_data',
() => populationData
.where((element) => element['city_code'] == item['city_code'])
.toList()
.map((element) => {'year': element['year'], 'population': element['population']})
.toList());
}