[英]Iterating over the individual values of an array inside an object
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 : 我正在使用
Object.keys
遍历上面的对象常量,下面是for循环:
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]])
, 问题在于此语句
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 :
,但即使经过该答案中的所有解决方案(Eric的最后一个解决方案看起来很有希望,但仍不能解决我的问题),所以我如何访问其中的属性:
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"
. 我想要的是字符串
"bangalore city"
。
Thank you. 谢谢。
Alex-z. 亚历克斯
@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: @AlexChar有正确的答案 (
console.log(all_locations[Object.keys(all_locations)[i]][j])
),但是您可以通过使用遍历数组和/的函数样式轻松避免此类问题或为变量使用语义名称:
Object.keys(all_locations).forEach(function(division){
all_locations[division].forEach(function(district) {
console.log(district);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.