Gammer
Gammer

Reputation: 5608

Jquery cannot access array outside of loop

I am getting a strange behavior from the following code. The following code is from ajax success, And console.log(positions); inside loop works fine, But outside it gives me nothing.

success: function (data) {
    var positions = [];

    $.each(data, function (index, value) {
        $.each(value, function (index1, value1) {
            positions.push({
                lat: value1.rider_location.lat,
                lng: value1.rider_location.lng,
            });
            //This works fine | I can get the results. But after commenting out the below line then the last `console.log(positions)` doesn't shows anything.
             console.log(positions);
        });
    });
    console.log(positions);
}

The data from the Ajax gives me the following results then i loop through it and assign the values to positions.

enter image description here

Indside the loop gives me the following results :

enter image description here

And outside of loop console.log(positions) gives no exception as well as no results.

Upvotes: 1

Views: 985

Answers (2)

Ivar
Ivar

Reputation: 6818

Your data is not an array but an object. Using $.each() on it means that it will loop over all of it's properties, which is why it does not work as you expect it. You probably want to loop over data.riders. Also there is no other array to loop over, so the second loop should not be there:

var data = {
    riders: [{
            rider_location: {
                lat: 2,
                lng: 3
            }
        },
        {
            rider_location: {
                lat: 4,
                lng: 5
            }
        }
    ]
};

var positions = [];

$.each(data.riders, function(index, value) {
    positions.push({
        lat: value.rider_location.lat,
        lng: value.rider_location.lng,
    });
});

console.log(positions);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Eladian
Eladian

Reputation: 958

Given the format of the data returned I would try:

It seems as if you're trying to loop through rider_location with the second loop, but rider_location is an object, so you can just access its properties.

success: function (data) {
    var positions = [];

    $.each(data.riders, function (index, value) {
           positions.push({
                lat: value.rider_location.lat,
                lng: value.rider_location.lng,
            });
    });
    console.log(positions);
}

PS feel free to rep me :)

Upvotes: 0

Related Questions