Reputation: 23
I have an array looking like this
final value = [
{
'category': 'Social Life',
'data': [
{'amount': 2000, 'content': 'thanks'}
]
},
{
'category': 'Food',
'data': [
{'amount': 2000, 'content': 'thanks'},
{'amount': 2000, 'content': 'thanks'}
]
}
]
I want to calculate the amount of each category using the fold()
method, but I don't know how to implement it
i want them look like this in my new variable
final newValue = [
{
'category': 'Social Life',
'amount': //the amount for 'Social Life' category,
},
{
'category': 'Food',
'amount': //the amount for 'Food' category,
}
]
Upvotes: 0
Views: 194
Reputation: 31279
This should do the trick.
void main() {
final value = [
{
'category': 'Social Life',
'data': [
{'amount': 2000, 'content': 'thanks'}
]
},
{
'category': 'Food',
'data': [
{'amount': 2000, 'content': 'thanks'},
{'amount': 2000, 'content': 'thanks'}
]
}
];
print(combineData(value));
// [{category: Social Life, amount: 2000}, {category: Food, amount: 4000}]
}
List<Map<String, Object>> combineData(List<Map<String, Object>> value) => value
.map((entry) => {
'category': entry['category'],
'amount': (entry['data'] as List<Map<String, Object>>).fold<int>(
0, (prev, element) => prev + (element['amount'] as int))
})
.toList();
Upvotes: 2