循环套循环再套循环，如何优化？

``````[{
"_id": "63807adbe78529ed328257b3",
"email": "zanghai@xxx.com",
"rewards": [{
"date": "2022-08-13 00:00:00",
"reward": "周：人物周刊"
}]
}, {
"_id": "63807adbe78529ed328257b5",
"email": "yangze@xxx.com",
"rewards": [{
"date": "2022-08-20 00:00:00",
"reward": "周：人物周刊"
}, {
"date": "Q3",
"reward": "签框英雄"
}, {
"date": "Q2",
"reward": "季度之星"
}]
}]``````

``````[{
"_id": "6380890fe18762bdfe8017e6",
"name": "周：人物周刊",
"integral": 5
}, {
"_id": "6380890fe18762bdfe8017f3",
"name": "签框英雄",
"integral": 15
}, {
"_id": "6380890fe18762bdfe8017f9",
"name": "季度之星",
"integral": 40
}]``````

``````[{
"_id": "63807adbe78529ed328257b3",
"email": "zanghai@bj.baidu.com",
"integral": 5
}, {
"_id": "63807adbe78529ed328257b5",
"email": "yangze@bj.baidu.com",
"integral": 60
}]``````

``````let ranking = []
let userRewards = await mongoose.userRewards.find() // 第一条查询结果
let integralTable = await mongoose.integralTable.find() // 第二条查询结果
userRewards.forEach(currentValue => {
let rewardsintegral = 0
currentValue.rewards.forEach(item => {
integralTable.forEach(target => {
if (target.name == item.reward) {
rewardsintegral += target.integral
}
})
})
ranking.push({
email: currentValue.email,
integral: rewardsintegral
})
})
res.send(integralTable)``````

2 个回答
✓ 已被采纳

``````let userRewards = [{
"_id": "63807adbe78529ed328257b3",
"email": "zanghai@xxx.com",
"rewards": [{
"date": "2022-08-13 00:00:00",
"reward": "周：人物周刊"
}]
}, {
"_id": "63807adbe78529ed328257b5",
"email": "yangze@xxx.com",
"rewards": [{
"date": "2022-08-20 00:00:00",
"reward": "周：人物周刊"
}, {
"date": "Q3",
"reward": "签框英雄"
}, {
"date": "Q2",
"reward": "季度之星"
}]
}]
let integralTable = [{
"_id": "6380890fe18762bdfe8017e6",
"name": "周：人物周刊",
"integral": 5
}, {
"_id": "6380890fe18762bdfe8017f3",
"name": "签框英雄",
"integral": 15
}, {
"_id": "6380890fe18762bdfe8017f9",
"name": "季度之星",
"integral": 40
}]

let integralTableMap = Object.fromEntries(integralTable.map(({name,integral})=>([name,integral])));
// {周：人物周刊: 5, 签框英雄: 15, 季度之星: 40}
userRewards.map(({rewards, ...other})=>{
other.integral = rewards.reduce((acc,cur)=>{
acc = acc + integralTableMap[cur.reward] || 0;
return acc;
},0)
return other;
})``````

`name`匹配，这不就是给自己挖坑，费力不讨好的活儿嘛，不应该后端给组合好？

你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进