【问题标题】:Nodejs array object not updatingNodejs 数组对象不更新
【发布时间】:2023-01-17 03:03:50
【问题描述】:

我正在从猫鼬数据库中获取数据。它有一些数组,其中包含我需要从其他 api 获取数据的 id。一切正常,但是当我在 for 循环中像这样更改数组对象时 team[i].teamPlayersDetails = playerss; 它没有改变我什至可以看到玩家有数据但它没有改变团队。

const getAllTeams = async (req, res) => {
    let team = await Team.find();
    var userids = [];
    var usersdata = [];

    for (let i = 0; i < team.length; i++) {
        for (let j = 0; j < team[i].teamPlayers.length; j++) {
            userids.push(team[i].teamPlayers[j])
        }
    }
    var data = {
        'ids': userids
    }

    await axios.post(`http://localhost:3000/auth/getMultipleUserByUserID`, data)
        .then(async function (response) {
            usersdata = response.data.data
        });

    for (let i = 0; i < team.length; i++) {
        playerss = [];

        team[i].teamPlayers.forEach(player_id => {
            playerss.push(usersdata.find(p => p.userID === player_id.toString()))
            team[i].teamPlayersDetails = playerss;
        })
    }

    if (!team) {
        return res.status(200).json({ message: "user not found", success: false })
    }

    return res.status(200).json({ message: "success", success: true, data: team })
};

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    而不是 forEach 我建议你使用经典的 for 循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多