简体   繁体   English

无法循环遍历 node.js 中的嵌套 object

[英]Failing to Loop through a nested object in node.js

i am trying to loop through a nested object and save the data to my cloud firestore database but it is not working,我正在尝试遍历嵌套的 object 并将数据保存到我的云 firestore 数据库,但它不起作用,

this is the structure of the object i have retrieved from an API call,这是我从 API 调用中检索到的 object 的结构,

{
    "count": 133,
    "filters": {
        "dateFrom": "2021-04-12",
        "dateTo": "2021-04-22",
        "permission": "TIER_ONE"
    },
    "matches": [
        {
            "id": 304061,
            "competition": {
                "id": 2021,
                "name": "Premier League",
                "area": {
                    "name": "England",
                    "code": "ENG",
                    "ensignUrl": "https://upload.wikimedia.org/wikipedia/en/a/ae/Flag_of_the_United_Kingdom.svg"
                }
            },
            "season": {
                "id": 619,
                "startDate": "2020-09-12",
                "endDate": "2021-05-23",
                "currentMatchday": 31,
                "winner": null
            },
            "utcDate": "2021-04-12T17:00:00Z",
            "status": "SCHEDULED",
            "matchday": 31,
            "stage": "REGULAR_SEASON",
            "group": "Regular Season",
            "lastUpdated": "2021-04-12T16:51:35Z",
            "odds": {
                "homeWin": 3.43,
                "draw": 3.31,
                "awayWin": 2.15
            },
            "score": {
                "winner": null,
                "duration": "REGULAR",
                "fullTime": {
                    "homeTeam": null,
                    "awayTeam": null
                },
                "halfTime": {
                    "homeTeam": null,
                    "awayTeam": null
                },
                "extraTime": {
                    "homeTeam": null,
                    "awayTeam": null
                },
                "penalties": {
                    "homeTeam": null,
                    "awayTeam": null
                }
            },
            "homeTeam": {
                "id": 74,
                "name": "West Bromwich Albion FC"
            },
            "awayTeam": {
                "id": 340,
                "name": "Southampton FC"
            },
            "referees": [
                {
                    "id": 11430,
                    "name": "Simon Hooper",
                    "role": "MAIN_REFEREE",
                    "nationality": "England"
                },
                {
                    "id": 11570,
                    "name": "Harry Lennard",
                    "role": "ASSISTANT_N1",
                    "nationality": "England"
                },
                {
                    "id": 11505,
                    "name": "Derek Eaton",
                    "role": "ASSISTANT_N2",
                    "nationality": "England"
                },
                {
                    "id": 11585,
                    "name": "Craig Pawson",
                    "role": "FOURTH_OFFICIAL",
                    "nationality": "England"
                },
                {
                    "id": 11487,
                    "name": "Kevin Friend",
                    "role": "VIDEO_ASSISTANT_REFEREE",
                    "nationality": "England"
                }
            ]
        },
        {
            "id": 303253,
            "competition": {
                "id": 2002,
                "name": "Bundesliga",
                "area": {
                    "name": "Germany",
                    "code": "DEU",
                    "ensignUrl": "https://upload.wikimedia.org/wikipedia/commons/b/ba/Flag_of_Germany.svg"
                }
            },
            "season": {
                "id": 599,
                "startDate": "2020-09-18",
                "endDate": "2021-05-15",
                "currentMatchday": 28,
                "winner": null
            },
            "utcDate": "2021-04-12T18:30:00Z",
            "status": "SCHEDULED",
            "matchday": 28,
            "stage": "REGULAR_SEASON",
            "group": "Regular Season",
            "lastUpdated": "2021-04-12T14:42:35Z",
            "odds": {
                "homeWin": 2.8,
                "draw": 3.72,
                "awayWin": 2.36
            },
            "score": {
                "winner": null,
                "duration": "REGULAR",
                "fullTime": {
                    "homeTeam": null,
                    "awayTeam": null
                },
                "halfTime": {
                    "homeTeam": null,
                    "awayTeam": null
                },
                "extraTime": {
                    "homeTeam": null,
                    "awayTeam": null
                },
                "penalties": {
                    "homeTeam": null,
                    "awayTeam": null
                }
            },
            "homeTeam": {
                "id": 2,
                "name": "TSG 1899 Hoffenheim"
            },
            "awayTeam": {
                "id": 3,
                "name": "Bayer 04 Leverkusen"
            },
            "referees": []
        }]}

this is my attempt to loop through the matches section of my object, i want to be able to iterate through each match while still being able to access sub objects within each iteration and set data in my cloud firestore database这是我尝试遍历我的 object 的匹配部分,我希望能够遍历每个匹配,同时仍然能够在每次迭代中访问子对象并在我的云 firestore 数据库中设置数据

   axios.request(options).then(function(response) {



    //console.log(typeof response); // check the type of response returning already in JSON format
    //console.log(response); // check the response object and based on key/values process it 

    const data = response.data; // if resp contains the data you will get it here.


    //console.log(response.data);

    /* for (let data1 in data.pagination) {
       // from the sample response you shared in the question 
       console.log(data1) // prints the keys
       console.log(data.pagination.data1) // prints the values*/

    for (i = 0; i < data.count; i++) {

        // from the sample response you shared in the question 
        // console.log(index);
        // console.log(data.f[data1]) // prints the keys
        // //console.log(data.pagination.data1) // prints the values

        const soccerData = {
            name: `${data.matches[i].competition.name}`,
            id: `${data.matches[i].competition.id}`
        };
        return db.collection('matches').doc(`${data.matches[i].id}`)
            .set(soccerData).then(() =>
                console.log('data written to database'));




    }


}).catch(function(error) {
    console.error(error);
});
 

To loop over matches use:要循环匹配使用:

 response.data.matches.forEach(match => { // do something with the match } )

Instead of the for loop.而不是 for 循环。 You can then do然后你可以做

 const soccerData = { name: `${match.competition.name}`, id: `${match.competition.id}` }

and also:并且:

 return db.collection('matches').doc(`${match.id}`).set(soccerData).then(() => console.log('data written to database'));

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

相关问题 使用 AWS ec2.describeInstances 在 node.js 中从嵌套对象中提取数据 - Extracting data from nested object with AWS ec2.describeInstances in node.js 如何使用 node.js 更新 firestore 中的嵌套字段? - How to update a nested field in firestore using node.js? 为什么我的示例应用程序 Elastic Beanstalk + Node.js 总是失败? - Why is my sample application Elastic Beanstalk + Node.js keep failing? 部署到 k8s 集群的非常简单的 node.js 应用程序,端口转发失败 - Very simple node.js application deployed to k8s cluster, port-forwarding is failing 通过 Node.js 和 Axios 从 AWS 发送外部请求时出错 - Error when sending an external request from AWS through Node.js and Axios Email 没有通过 sendgrid 发送,也没有显示任何错误/node.js - Email is not sending through sendgrid and also not showing any error/ node.js 有没有办法通过SendGrid在node.js中获取空灵的email消息ID? - Is there a way to get ethereal email message ID in node.js through SendGrid? 直接下载存储在S3 bucket中的文件到React客户端,而不是通过Node.js服务器 - Download file stored in S3 bucket directly to React client, instead of passing through Node.js server Node.js MongoDB ECONNREFUSED - Node.js MongoDB ECONNREFUSED JavaScript 与 Node.js - JavaScript vs Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM