首页 > 解决方案 > 如何循环遍历 JSON 数据

问题描述

我已将一些 JSON 数据导入我的控制台,并尝试在文档中显示少量数据。这是我拥有的数据的一个示例:

   {"hours":[{"airTemperature":[{"source":"sg","value":14.03},{"source":"noaa","value":8.06},{"source":"dwd","value":14.03}],"time":"2018-09-29T00:00:00+00:00","waveHeight":[{"source":"sg","value":0.44},{"source":"meto","value":1.28},{"source":"meteo","value":0.44},{"source":"noaa","value":0.78},{"source":"dwd","value":0.63}]},{"airTemperature":[{"source":"sg","value":13.61},{"source":"noaa","value":8.12},{"source 

数据链接到我在地图上的标记,我试图将一些数据放入我在我的 html 文件中设置的文本区域。例如,我想遍历数据并每六小时从 noaa 中获取 airTemp 和 waveHeight 的所有值。虽然我知道我需要一个循环来做到这一点,但就我的技能而言,我已经遇到了一些障碍,并且很难在任何我能理解的地方找到参考。非常感谢任何正确方向的指针。到目前为止,这是我的 js:

            // create locations coordinates offshore close to named town to get marine information for that area.
    var locations = [
        ["Penzance", 50.070092, -5.767671],
        ["St Ives", 50.250562, -5.491298],
        ["Newquay", 50.440782, -5.126195],
        ["Bude", 50.802900, -4.614876],
        ["Woolacombe", 51.166777, -4.344528]
    ];


  //set parameters for api information we need
    const params = 'waveHeight,airTemperature';




//initiate map
    function initMap() {

        var map = new google.maps.Map(document.getElementById('map-canvas'), {
            zoom: 9,
            center: { lat: 50.738, lng: -4.002  }
        });




        // Info Window initialize
        var infoWindow = new google.maps.InfoWindow(),
            marker, i;


        // marker icon
        var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
        //set markers on map
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: { lat: locations[i][1], lng: locations[i][2] },
                map: map,
                title: locations[i][0],
                icon: image
            });


// gets relevant api data when offshore marker is clicked
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    fetch(`https://api.stormglass.io/point?lat=${locations[i][1]}&lng=${locations[i][2]}&params=${params}`, {
                        headers: {
                            'Authorization': 'MY_ACCESS_KEY'
                        }
                    }).then(function(response) {
                        return response.json();
                    }).then(function(data) {
                        console.log(data);


                      document.getElementById("waves").innerHTML = data;
                    });

                    infoWindow.setContent(locations[i][0]);
                    infoWindow.open(map, marker);

                };


            })(marker, i));


        }

}



initMap();

标签: javascriptjson

解决方案


推荐阅读