javascript - 使用reduce获取对象的总和
问题描述
我想汇总 selectedIds 数组中的所有详细信息。
return [
{
id: 1244,
name: "Installment 1",
amount: 10000,
due_date: new Date(),
particulars: [
{
id: 2415123,
name: "Development Fee",
amount: 5000,
},
{
id: 14123,
name: "Library Fee",
amount: 3000,
},
{
id: 5123151,
name: "Sports Fee",
amount: 2000,
},
]
},
{
id: 1412,
name: "Installment 2",
amount: 6000,
due_date: new Date(),
particulars: [
{
id: 414,
name: "Development Fee",
amount: 5000,
},
{
id: 5123,
name: "Library Fee",
amount: 3000,
},
{
id: 515151,
name: "Sports Fee",
amount: 2000,
},
]
const selectedIds = [14123, 414];
在对象中,我想要对 selectedIds 数组中的所有细节进行总和。我试图使用数组函数来获得结果。这是我能想到的。
const selectedInstallments = this.studentInstallments
.filter((installment) =>
installment.particulars.some((particular) =>
this.selectedParticulars.includes(particular.id)
)
)
.map((installment) => installment.particulars);
console.log(selectedInstallments);
const sumParticularReducer = (acc, current) => {
return acc;
};
我不知道如何使用 reduce 来获得结果。
解决方案
请尝试此代码。
const selectedIds = [14123, 414];
const sum = arr.reduce((prev, cur) => {
return prev + cur.particulars.reduce((old, item) => (
selectedIds.indexOf(item.id) >= 0 ? old + item.amount : old
), 0);
}, 0);
console.log(sum);
推荐阅读
- c# - Unity 3D CS0246 问题
- javascript - 如何在 Angular 12 中配置“crypto-random-string”而不会出现编译错误?
- sql-server - 在列表框中显示表名 (VB)
- python - 使用字符串方法提供参数以从状态中拆分和删除换行符
- python - Google OAuth:仅撤销对选定范围的授权(不是全部)
- firebase-authentication - Firesbase auth 回退异常:Java 语言异常
- java - 如何在数组中的每 5 个数字后开始一个新行?
- python - heroku git:remote -a 命令不起作用
- java - 如何在webflux中将spring boot websocket文本消息转换为自定义java对象(bean或DTO)
- android - 如何使用`flow`从`repository`到`viewModel`获取firebase`childEventListener`的持续更新?