简体   繁体   中英

Better way to push elements with two for loops

I have a function that calls on an api that runs 2 for loops to get the API elements. I am trying to push those elements in a nested push. is there a better way to do this? below is my code.

    axios.get(url+'api_key='+apiKey +'&address.city='+city+'&address.postal_code='+zipCode+'&address.state_code='+state+'&name='+orgName)

        .then(res => {
            /*If whitePages brings in less than 1 results, moves to googleAPI call */
            if(parseInt(res.data.count_business) < 1){
                fetchGooglePlace(data)

            }else{
                console.log('RUNNING WHITEPAGES');


                for(let i =0; i < res.data.business.length; i++ ){

                    churchListing.push({

                        name: res.data.business[i].name + '\n\r',
                        address: res.data.business[i].found_at_address.street_line_1 + '\n\r',

                    });

                    /*Second loop to fetch phone numbers from array in that i am trying to include in the nested push().  
                    for (let x = 0; x < res.data.business[i].phones.length; x++) {
                        phone: res.data.business[i].phones[x].phone_number ,
                    }

                }
                    writeStream(churchListing);
            }
        })
        .catch(err => {
            console.log(err)
        });
}

the JSON array for phone numbers looks like this.

 "phones": [
        {
            "id": "Phone.46c16fef-a2e1-4b08-cfe3-bc7128b6e19a",
            "phone_number": "+16187459424",
            "line_type": "Landline"
        }
    ],

I fixed my own problem. I wanted to push and array of objects with two for loops. below is my code and works.

for(let i =0; i < res.data.business.length; i++ ){
                        for (let x = 0; x < res.data.business[i].phones.length; x++) {
                            churchListing.push({
                                name: res.data.business[i].name + '\n\r',
                                address: res.data.business[i].found_at_address.street_line_1 + '\n\r',
                                phone: res.data.business[i].phones[x].phone_number + '\n\r',
                            });
                        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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