var City ={
"City1": [{"name": "Place 1"},{"name": "Place 2"},{"name": "Place 3"}],
"City2":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}],
"City3":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}]
};
我想使用JavaScript循环获取第一个城市名称,然后循环获取其位置,然后获取第二个城市及其位置等等。
答案 0 :(得分:4)
您可以使用for
循环遍历City
对象的所有属性:
for (var key in City) {
if (City.hasOwnProperty(key)) {
var values = City[key];
// "key" will be City1, City2, ...
// "values" will be the corresponding array through which
// you can loop
}
}
答案 1 :(得分:2)
尝试使用Object.keys()
,Array.prototype.forEach()
var City = {
"City1": [{
"name": "Place 1"
}, {
"name": "Place 2"
}, {
"name": "Place 3"
}],
"City2": [{
"name": "My Place 1"
}, {
"name": "My Place 2"
}, {
"name": "My Place 3"
}],
"City3": [{
"name": "My Place 1"
}, {
"name": "My Place 2"
}, {
"name": "My Place 3"
}]
};
Object.keys(City).forEach(function(value, key) {
console.log(value);
City[value].forEach(function(v, k) {
console.log(v.name)
})
});
答案 2 :(得分:0)
for (let key in City) {
let value = City[key];
console.log(key);
for (i = 0; i <= value.length; i++) {
console.log(value[i]);
}
}