问答详情
源自:8-1 概念与继承

如何输出这个json里面的数据

{

    "name": "中国",

    "province": [{

        "name": "黑龙江",

        "cities": {

            "city": ["哈尔滨", "大庆"]

        }

    }, {

        "name": "广东",

        "cities": {

            "city": ["广州", "深圳", "珠海"]

        }

    }, {

        "name": "台湾",

        "cities": {

            "city": ["台北", "高雄"]

        }

    }, {

        "name": "新疆",

        "cities": {

            "city": ["乌鲁木齐"]

        }

    }]

}

//我要输出这些城市名,难道要多层for语句吗?

提问者:会飞的柠檬 2016-01-11 15:48

个回答

  • 李晓健
    2016-01-11 21:24:22
    已采纳

    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);

    不知道你想要哪一个?

  • qq_慕慕947699
    2020-04-15 18:35:49

    console.log(data.province.reduce((a, b) => {

          return b.cities && b.cities.city && a.concat(b.cities.city)

        }, []))