不使用键访问 json 对象中的数组
accessing arrays in json object without using keys
我有一个 JSON
数组对象
data = {
China: ["Guangzhou","Fax"],
Majorette: ["Fungous","Godzilla"],
Bhutan: ["Thimphu","Parr","Photofinishing"]
}
我想访问数组中的城市名称而不明确提及国家名称,因为列表很长。
var cities = [];
for(var i in data.China) {
cities[i] = data.China[i];
}
所有国家应该怎么办?
for (var key in data) {
var citiesArray = data[key]; // cities for the current country
// your code
}
有效地遍历城市对象:
Object.keys(data).forEach(function(key) {
// In here, data[key] is each array of cities.
});
现在,根据我从您的问题中了解到的情况,您希望将多维 object/array 缩减为一个城市平面数组:
var cities = Object.keys(data).reduce(function(arr, key) {
return arr.concat(data[key]);
}, []);
请注意Object.keys
以及Array.prototype.forEach
和Array.prototype.reduce
是IE9及以上的功能
这应该填充城市数组:
var data = {
China: ["Guangzhou","Fax"],
Majorette: ["Fungous","Godzilla"],
Bhutan: ["Thimphu","Parr","Photofinishing"]
}
var cities = [];
for(var i in data){
if(data.hasOwnProperty(i)){
for(var j in data[i] ){
if(data[i].hasOwnProperty(j)){
cities.push(data[i][j]);
}
}
}
}
console.log(cities);
for (var country in data){
for(var i=0;i<data[country].length;i++){
console.log (data[country][i]);
}
}
我有一个 JSON
数组对象
data = {
China: ["Guangzhou","Fax"],
Majorette: ["Fungous","Godzilla"],
Bhutan: ["Thimphu","Parr","Photofinishing"]
}
我想访问数组中的城市名称而不明确提及国家名称,因为列表很长。
var cities = [];
for(var i in data.China) {
cities[i] = data.China[i];
}
所有国家应该怎么办?
for (var key in data) {
var citiesArray = data[key]; // cities for the current country
// your code
}
有效地遍历城市对象:
Object.keys(data).forEach(function(key) {
// In here, data[key] is each array of cities.
});
现在,根据我从您的问题中了解到的情况,您希望将多维 object/array 缩减为一个城市平面数组:
var cities = Object.keys(data).reduce(function(arr, key) {
return arr.concat(data[key]);
}, []);
请注意Object.keys
以及Array.prototype.forEach
和Array.prototype.reduce
是IE9及以上的功能
这应该填充城市数组:
var data = {
China: ["Guangzhou","Fax"],
Majorette: ["Fungous","Godzilla"],
Bhutan: ["Thimphu","Parr","Photofinishing"]
}
var cities = [];
for(var i in data){
if(data.hasOwnProperty(i)){
for(var j in data[i] ){
if(data[i].hasOwnProperty(j)){
cities.push(data[i][j]);
}
}
}
}
console.log(cities);
for (var country in data){
for(var i=0;i<data[country].length;i++){
console.log (data[country][i]);
}
}