作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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'}
]
}
]
我想使用
fold()
方法计算每个类别的数量,但是我不知道如何实现它
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,
}
]
最佳答案
这应该可以解决问题。
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();
关于arrays - 如何将数组元素int Dart相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62622870/
我是一名优秀的程序员,十分优秀!