Search code examples
javascriptnested-loopshoisting

Javascript - how to iterate through nested array with arrays and objects and why is my code not working?


I have an array with many nested arrays and objects. My code doesn't work and after looking at it over and over again, I don't understand why. Its hard to explain what I mean (sorry if my title question was also not very clear, but I didn't know how to explain what I mean, if I don't know whats wrong in my code), so I put my 2 questions insight my code as comments - I hope its understandable! Thanks a lot for any ideas.

var trips= [{
   "Air": {
        "OriginDestinationOptions": {
            "OriginDestinationOption": [{
                "Flight": [{
                    "DepartureAirport": {
                        "LocationCode": "JFK"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "SVO"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                }, {
                    "DepartureAirport": {
                        "LocationCode": "SVO"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "TXL"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }

                },
                {
                    "DepartureAirport": {
                        "LocationCode": "TXL"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "LHR"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }

                }],
                "ElapsedTime": 915
            }, {
                "Flight": [{
                    "DepartureAirport": {
                        "LocationCode": "LHR"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "LAX"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                }, {
                    "DepartureAirport": {
                        "LocationCode": "LAX"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "TXL"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                },
                 {
                    "DepartureAirport": {
                        "LocationCode": "TXL"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "LHR"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }

                }],
                "ElapsedTime": 1425
            }]
        },
        "DirectionInd": "Return"
    }
}, 
{
    "Air": {
        "OriginDestinationOptions": {
            "OriginDestinationOption": [{
                "Flight": [{
                    "DepartureAirport": {
                        "LocationCode": "JFK"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "SVO"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                }, {
                    "DepartureAirport": {
                        "LocationCode": "SVO"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "LHR"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                }],
                "ElapsedTime": 915
            }, {
                "Flight": [{
                    "DepartureAirport": {
                        "LocationCode": "LHR"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "SVO"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                }, {
                    "DepartureAirport": {
                        "LocationCode": "SVO"
                    },
                    "ArrivalAirport": {
                        "LocationCode": "JFK"
                    },
                    "MarketingAirline": {
                        "Code": "SU"
                    }
                }],
                "ElapsedTime": 1125
            }]
        },
        "DirectionInd": "Return"
    }        
}];

My code:

var flightObjects = [];

     function getAirportNameToLocation(obj) {
         var allTrips = [];
         for (var i = 0; i < obj.length; i++) {                  

      allTrips.push(obj[i].Air.OriginDestinationOptions.OriginDestinationOption)
         }

         for (var i = 0; i < allTrips.length; i++) {

             var toDestinationFlightsTemp = [];
             var returnFlightsTemp = [];
             //first FlightsSegment object --> to destination flights
             var flightsToLoc = allTrips[i][0];

             //second FlightsSegment object --> return flights
             var returnFlights = allTrips[i][1];

             console.log(toDestinationFlightsTemp)

1.) when I console log 'toDestinationFlights'-I get an empty array, but 2 lines below when I push ALSO (same as I console log before) toDestinationFlights to my flightObjects object and return that object, Im actually not getting back an empty array, but values. I don't know why.

             console.log("test", toDestinationFlightsTemp)
             flightObjects.push({

2.) What was intended here: toDestinationFlights: toDestinationFlightsTemp.concat(returnFlights[0]) - I want the values from toDestinationFlightsTemp and the first value from returnFlightsTemp this doesnt work because again, somehow Im getting an empty array

                 toDestinationFlights: toDestinationFlightsTemp, //This for whatever reason works fine
                 returnFlights: returnFlightsTemp
             })

             flightsToLoc.Flight.forEach(function(flightTo, i) {
                 toDestinationFlightsTemp.push(flightTo.DepartureAirport.LocationCode);
             })

             returnFlights.Flight.forEach(function(flightTo, i) {
             returnFlightsTemp.push(flightTo.DepartureAirport.LocationCode)
             })
         }
         toDestinationFlightsARIVALTemp = toDestinationFlightsTemp.concat(returnFlightsTemp[0]);
     }
     getAirportNameToLocation(trips)

     flightObjects;

Solution

  • Here's why you're seeing what looks like unexpected behavior:

    First you define variable outside the function flightObjects. Then you make a loop loop that will run twice:

    for (var i = 0; i < allTrips.length; i++)
    

    Then inside that loop you initialize a variable:

    var toDestinationFlightsTemp = [];
    

    This gets redefined every time through the loop. You console.log it and it's still an empty array because you haven't touched it.

    Next you push that empty array onto the global flightObjects:

    flightObjects.push({
                toDestinationFlights: toDestinationFlightsTemp, //This for whatever reason works fine
                returnFlights: returnFlightsTemp
            })
    

    This doesn't actually work fine — flightObjects.toDestinationFlights is now pointing to the same empty array as toDestinationFlightsTemp. The first time through the loop, both print empty arrays. But then, after you've console.loged it, you add elements to it:

     flightsToLoc.Flight.forEach(function(flightTo, i) {
                toDestinationFlightsTemp.push(flightTo.DepartureAirport.LocationCode);
            })
    

    Since toDestinationFlightsTemp and flightObjects.toDestinationFlights point to the same array, both toDestinationFlightsTemp and flightObjects.toDestinationFlights have the element you pushed into the array.

    Now you loop again. On this loop you redefine toDestinationFlightsTemp and point it to a new empty array. But flightObjects still points to the same array and has a reference to the elements you pushed the first time through your loop. So now when you get to the console.logs toDestinationFlightsTemp is empty, but flightObjects still has the elements you pushed the first time though the loop. So you see those when you console.log it.

    I think what you were intending to do would happen if you moved this up before you try to push the values into flightObjects:

            flightsToLoc.Flight.forEach(function(flightTo, i) {
                toDestinationFlightsTemp.push(flightTo.DepartureAirport.LocationCode);
            })