Ad

Loop Through Object Items

- 1 answer

I have pretty complicated object and I need to loop through multiple levels of items. This got tricky very fast and Im stuck now.

What I've tried (Note that I added an error I get):

var stuffCount = Object.keys(stuff).length;

//Loop through initial items in object
for( i = 0; i < stuffCount; i++ ) {

    // Error occurs on this line:
    // Uncaught TypeError: Cannot read property 'points' of undefined
    var pointCount = stuff[i].points.length; 

    var coordinates = [];

    //Loop through points in initial items
    for( r = 0; r < pointCount; r++ ) {

        coordinates.push(new google.maps.LatLng( 
            stuff[i].points[r].lat, 
            stuff[i].points[r].lng ));
    }

}

Object: It's even more complicated but I made it as simple as possible for the sake of this question.

var stuff = {

    first: {

        center: {
            lat: 11,
            lng: 22
        },
        points: [
            {
                lat: 11,
                lng: 22
            },
            {
                lat: 33,
                lng: 44
            },
            {
                lat: 55,
                lng: 66
            },
        ]
    },

    second: {

        center: {
            lat: 11,
            lng: 22
        },
        points: [
            {
                lat: 11,
                lng: 22
            },
            {
                lat: 33,
                lng: 44
            },
            {
                lat: 55,
                lng: 66
            },
        ]
    },

    third: {

        center: {
            lat: 11,
            lng: 22
        },
        points: [
            {
                lat: 11,
                lng: 22
            },
            {
                lat: 33,
                lng: 44
            },
            {
                lat: 55,
                lng: 66
            },
        ]
    },
}

Im trying to make code smaller by using loops. It's used to show polygons on Google Maps. I could do it one by one but code is going to be pretty big because I have like 100 of them + I want it to be dynamic so that I can easily add new polygons in future without changing a lot of code.

What's wrong with my code?

Ad

Answer

The problems is that you are trying to retrieve keys from your stuff object using a numbered index. You actually don't need the count of keys, use a for...in loop instead like so:

//Loop through initial items in object
for(var i in stuff) {

    // Error occurs on this line:
    // Uncaught TypeError: Cannot read property 'points' of undefined
    var pointCount = stuff[i].points.length; 

    var coordinates = [];

    //Loop through points in initial items
    for( r = 0; r < pointCount; r++ ) {

        coordinates.push(new google.maps.LatLng( 
            stuff[i].points[r].lat, 
            stuff[i].points[r].lng ));
    }

}
Ad
source: stackoverflow.com
Ad