gpt4 book ai didi

arrays - 如何将数组元素int Dart相加

转载 作者:行者123 更新时间:2023-12-03 04:20:58 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com