javascript - 如何循环遍历 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]}¶ms=${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();
解决方案
推荐阅读
- android - ImageView Clickable 在 Fragment 上不起作用 - Android
- node.js - 访问 Promise 之外的变量
- python - AttributeError:“NoneType”对象没有属性“startswith”
- java - 我可以阻止 java 告诉 macOS 窗口管理器将焦点从当前窗口移开吗?
- grammar - 导入 liquibase.util.grammar 无法解析
- java - 放心错误解析消息:“无效的 UTF-8 中间字节 0x20”
- c++ - 多重继承同名且无歧义
- php - 如何使用for循环,PHP中相同mysqli_query中的IN运算符
- meteor - 如何在 jest env 中存根或忽略流星/会话?
- vba - VBA-根据文本将数据从一张纸传输到另一张纸并放入另一张纸的特定位置