如何在JSON中访问数组中的数组值?

时间:2012-06-12 18:47:55

标签: javascript jquery json google-maps google-maps-api-3

如何在每个featurescondo元素中访问house数组的每个值? 我试过这样:

attr.features.name,

...但在网络控制台中弹出undefined

JSON

({condos:[{Address:'123 Fake St.', Lat:'56.645654', Lng:'23.534546', features:[{id:'1', name:'Swimming Pool'},{id:'2', name:'BBQ'},{..etc..}]},{... another condo ...},{...}],houses:[{Address:'1 Main Ave.', Lat:'34.765766', Lng:'27.8786674', features:[{...},{...}]},{... another house ...}, {...}]})

代码

    $.each(markers, function(type, elements) {
        $.each(elements, function(index, attr){
            // if it's a house - make house marker. if it's a condo - make condo marker.
            if (type == 'houses') {
                $('#map').gmap('addMarker', { 'features': attr.features.name, 'position': new google.maps.LatLng(parseFloat(attr.lat), parseFloat(attr.lng)), 'bounds':true, 'icon':'house.png' });
            }
            else if (type == 'condos') {
                $('#map').gmap('addMarker', { 'features': attr.features.name, 'position': new google.maps.LatLng(parseFloat(attr.lat), parseFloat(attr.lng)), 'bounds':true, 'icon':'condo.png' });
            }
        });
    });

1 个答案:

答案 0 :(得分:1)

你有一个带有两个数组的对象。您应该分别访问每个阵列

$(markers.condos).each(function(index, elem) {
    $('#map').gmap('addMarker', {
        'features': elem.features,
        'position': new google.maps.LatLng(parseFloat(elem.lat), parseFloat(elem.lng)),
        'bounds': true,
        'icon': 'condo.png'
    });
});​

markers.houses

相同