javascript - Loop through object items -


i have pretty complicated object , need loop through multiple levels of items. got tricky fast , im stuck now.

what i've tried (note added error get):

var stuffcount = object.keys(stuff).length;  //loop through initial items in object for( = 0; < stuffcount; i++ ) {      // error occurs on 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 more complicated made simple possible sake of 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 make code smaller using loops. it's used show polygons on google maps. 1 one code going pretty big because have 100 of them + want dynamic can add new polygons in future without changing lot of code.

what's wrong code?

the problems trying retrieve keys stuff object using numbered index. don't need count of keys, use for...in loop instead so:

//loop through initial items in object for(var in stuff) {      // error occurs on 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 ));     }  } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -