Is there any easy way convert List to other model data?
this is my model:
class Account {
String name;
double balance;
Account({required this.name, required this.balance});
}
class CategoryAccount {
String type;
List<Account> items;
CategoryAccount({required this.type, required this.items});
}
this is sourceData:
List<Account> sourceData = [
Account(name: 'cash', balance: 100),
Account(name: 'cash', balance: 200),
Account(name: 'bank', balance: 300),
Account(name: 'creditor', balance: 400),
];
I want sourceData convert to finalData:
List<CategoryAccount> finalData = [
CategoryAccount(
type: 'cash',
items: [
Account(name: 'cash', balance: 100),
Account(name: 'cash', balance: 200),
],
),
CategoryAccount(
type: 'bank',
items: [
Account(name: 'bank', balance: 300),
],
),
CategoryAccount(
type: 'creditor',
items: [
Account(name: 'creditor', balance: 300),
],
),
];
In Dart I saw the following method for a List : asMap(), but it's not doing what i expect: it use the list index as key. My questions:
Do you known anything in Dart libraries to do this ?
CodePudding user response:
You can use collection package like this:
var grouped = groupBy(
sourceData,
(Account element) => element.name,
);
var finalData = grouped.entries
.map((e) => CategoryAccount(type: e.key, items: e.value))
.toList();
for (var element in finalData) {
print("type = ${element.type}");//cash, bank, creditor
}
CodePudding user response:
Solution without using a package.
List<CategoryAccount> finalData = [];
for (var se in sourceData) {
final index = finalData.indexWhere((fe) => fe.type == se.name);
if (index >= 0) {
finalData[index].items.add(se);
} else {
finalData.add(CategoryAccount(type: se.name, items: [se]));
}
}