Reputation: 10230
hey guys i have a really complex array object literal , that i am trying to traverse , below is the object literal :
var all_locations = {
'bangalore city' : ['bangalore city'],
'bellary division' : ['bellary district' , 'koppala district' , 'davanagere district' ,
'shimoga district' , 'haveri district'],
'mangalore division' : ['dakshina kanada district' , 'chikkamagalur district' , 'upupi district'],
'kolar division' : ['kolar district' , 'chikkaballapura district' , 'bangalore rural district' ,
'citradurga district' , 'tumkur district'],
'raichur division' : ['raichur district' , 'yadgir district' , 'gulbarga district' , 'bidar district'],
'mysore division' : ['maysore district' , 'mandya district' , 'chamarajanagara district' , 'kodau district' ,
'hasan district'],
'hubli devision' : ['dharwad district' , 'gadag district' , 'belgaum district' ,
'bagalkote district' , 'bijapur district']
}
I am making use of Object.keys
to traverse the above object literal , with the below for loop :
for (var i = 0; i < Object.keys(all_locations).length ; i++) {
for (var j = 0; j < all_locations[Object.keys(all_locations)[i]].length ; j++) {
console.log(all_locations[Object.keys(all_locations)[i]])
}
}
the problem lies with this statement , console.log(all_locations[Object.keys(all_locations)[i]])
,
i am not accessing the array properties inside , which is what i want to do ?
I saw this thread on SO here. , but even after going through all the solutions in that answer (the last solution by Eric looked promising , but still did't solve my problem) , so how do i access the properties inside :
all_locations[Object.keys(all_locations)[i]] ??
EDIT ::
small example , on the 1st iteration of the loop i get the following result :
Array [ "bangalore city" ]
what i want is the string "bangalore city"
.
Thank you.
Alex-z.
Upvotes: 0
Views: 55
Reputation: 27823
@AlexChar has the right answer (console.log(all_locations[Object.keys(all_locations)[i]][j])
), of course, but you can easily avoid such problems by using the functional style of iterating over arrays and/or using semantic names for your variables:
Object.keys(all_locations).forEach(function(division){
all_locations[division].forEach(function(district) {
console.log(district);
});
});
Upvotes: 2