会飞的柠檬
2016-01-11 15:48
{
"name": "中国",
"province": [{
"name": "黑龙江",
"cities": {
"city": ["哈尔滨", "大庆"]
}
}, {
"name": "广东",
"cities": {
"city": ["广州", "深圳", "珠海"]
}
}, {
"name": "台湾",
"cities": {
"city": ["台北", "高雄"]
}
}, {
"name": "新疆",
"cities": {
"city": ["乌鲁木齐"]
}
}]
}
//我要输出这些城市名,难道要多层for语句吗?
var data = { "name": "中国", "province": [{ "name": "黑龙江", "cities": { "city": ["哈尔滨", "大庆"] } }, { "name": "广东", "cities": { "city": ["广州", "深圳", "珠海"] } }, { "name": "台湾", "cities": { "city": ["台北", "高雄"] } }, { "name": "新疆", "cities": { "city": ["乌鲁木齐"] } }] }; //方式一 var provinces = data.province; for(var i= 0,len=provinces.length;i<len;i++){ var citys = provinces[i].cities.city; console.log('-----------------'+provinces[i].name+'--------------') for(var j= 0,jlen=citys.length;j<jlen;j++){ console.log(citys[j]); } } //方式2 var citys2=[]; for(var x= 0,xlen=data.province.length;x<xlen;x++){ citys2 = citys2.concat(data.province[x].cities.city) } console.log(citys2);
不知道你想要哪一个?
console.log(data.province.reduce((a, b) => {
return b.cities && b.cities.city && a.concat(b.cities.city)
}, []))
JavaScript深入浅出
281111 学习 · 1020 问题
相似问题