多维数组JSON返回Object Object

时间:2016-12-03 22:39:01

标签: arrays json multidimensional-array

我的JSON就在这里......我想只有CITIES - 而不是剩余的CITIES,只有选项值里面的城市名称,然后我要插入到表单中。 但是我的脚本正在返回所有内容。我错过了什么吗?

代码在这里:

<script>
            $(function () {
           var shops =  new Array();
           var show_options = '';
           $.getJSON('shops.json', function(data) {
               for (var i = 0; i < data.cities.length; i++) {
                console.log('<option value="'+data.cities[i]+'>'+data.cities[i]+'</option>');
                   }

           });

        });
</script>

我正在进口的JSON文件

{       "cities":
            [{
                    "Bratislava":
                        [
                        {
                        "address": "– Supermarket KON-RAD - Cesta na Senec 24"
                        },
                        {
                        "address": "– ASTÉVIA - Predajňa zdravej výživy (OC CENTRAL) - Metodova 6"
                        },
                        {
                        "address": "– Paleo Dobre Dobroty –OC Fresh Market - Rožňavská 1"
                        },
                        {
                        "address": "– Bioobchod Slnečnica, - www.slnecnica.sk - Kvačalova 49"
                        },
                        {
                        "address": "– YEME – plnochutné potraviny - Tomášikova 46/A"
                        }
                        ],
                    "Banská Bystrica":
                        [
                        {
                        "address": "– Predajňa racionálnej výživy TT RACIO - www.ttracio.sk - Spojová 19"
                        },
                        {
                        "address": "– London tea&Natura Shop - www.londontea.sk - Horná 32"
                        }
                        ]
            }]
    }

1 个答案:

答案 0 :(得分:0)

请注意,data.cities是一个包含一个对象的数组,其键是城市名称,因此您需要迭代这些键:

$.getJSON('shops.json', function(data) {
  Object.keys(data.cities[0]).forEach(function (city) {
    console.log('<option value="' + city + '">' + city + '</option>');
  });
});

plunker:http://plnkr.co/edit/oQ6QAhyJCpvNNlQNtJu6?p=preview