循环套循环再套循环,如何优化?

我得第一条查询结果:

[{
    "_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
}]

也就是一个新的数组变量,其中每个元素包含 email 以及与第二条数据中匹配的 integral 数组累加
以下是我的代码:

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)

通过了三个循环实现,个人实在不满意,觉得应该有更便捷的方法
但个人能力浅薄,未能研究出来
在此还望大拿指点迷津

回复
阅读 748
2 个回答

image.png

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匹配,这不就是给自己挖坑,费力不讨好的活儿嘛,不应该后端给组合好?

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