繁体   English   中英

如何在javascript(node.js)API中使用map嵌套数组?

[英]How to map nested array in javascript(node.js) API?

let getOeReport = async (req, res) => {
    try {
       
        let searchFormatForReason = {
            "query": {

                "reasonCode": null,

            },
            "fields": {
                'reason': 1, '_id': 0
            }
        }
        let result = await oeDao.getOeReport(searchFormat)

        let resultReasons =
            result.map(async res =>
                res.sequences.map(inter =>
                    inter.interrupts.map((interrupts) => {
                        searchFormatForReason.query.reasonCode = interrupts.reason
                        reasonDao.getReasonByFields(searchFormatForReason)

                    })
                )
            )
        console.log(resultReasons)
        res.status(200).json({
            status: "Success",
            data: {
                result: result
            }
        });
    } catch (err) {
        console.log(err)
        res.status(400).json({
            status: "Failure"
        });
    }
};

在上面的代码中,如果我尝试控制结果原因意味着我得到 null。 结果变量具有嵌套的对象数组,因此,我需要中断数组内的“原因”值,该数组位于序列数组内,并且位于结果数组内。 我应该使用该值发出 API 请求,我可以将其推送到 resultReasons 数组中。 请有人帮助我...谢谢

let resultReasons =
        result.map(async res =>
            res.sequences.map(inter =>
                inter.interrupts.map((interrupts) => {
                    searchFormatForReason.query.reasonCode = interrupts.reason
                    reasonDao.getReasonByFields(searchFormatForReason)

                })
            )
        )

在这段代码中,您使用的是async ,因此您必须收到Promise ,因为您没有在该异步 function 中使用await我看不出保留它的原因,但是您可以按照以下方式添加 await下面的代码应该可以解决问题(您已经在getOeReport上使用了异步,因此它无需任何修改即可工作

let resultReasons =
        await result.map(async res =>
            res.sequences.map(inter =>
                inter.interrupts.map((interrupts) => {
                    searchFormatForReason.query.reasonCode = interrupts.reason
                    reasonDao.getReasonByFields(searchFormatForReason)

                })
            )
        )

But you are saying you get null which I don't understand how you are getting it, this because again you are using an async function within the first map, hence you must get a Promise , the only way I see your variable can be null如果result变量是 null,但它应该触发一个异常,所以你的 console.log 永远不会被执行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM