如何使用Ajax与jQuery过滤JSON响应并提取前5条数据生成日期和地表温度数组
Alright, let's tackle this. Even though the JSON structure uses dates as top-level keys (which is a bit unconventional), we can still easily extract the data you need to build your labels and data arrays. Here's the modified code with step-by-step explanations:
Solution Code
$.ajax({ dataType: "json", type: "GET", url: "https://www.infoclimat.fr/public-api/gfs/json?_ll=43.60426,1.44367&_auth=VkwDFAB%2BVnQALVRjDngELQRsAzZaLFJ1B3sBYgFvVisCZ1czA2QAYFY%2FVisOIQUwAy4EYA80AjlTNgZmXy1fI1Y3A24AZFY2AGxUNw47BC8EKAN%2BWmRSdQd7AWQBbFY3An9XMQNiAHxWOFYwDjsFLwMxBGUPOAIlUy8GYF80Xz9WNQNlAGpWMABtVDUOOgQvBCgDZVpkUmgHNwFjAWxWYQIwV2YDMgBrVj1WMw43BS8DNARkDzMCPVM0BmNfNF86VioDeAAaVkcAclR2DnwEZQRxA35aMFI0BzA%3D&_c=d2cc2bd980a89404afabf2e9b204309c", success: function(json) { // Step 1: Filter out only the date-time keys from the response const dateKeys = Object.keys(json).filter(key => /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(key) ); // Step 2: Get the first 5 dates (sort first if you need guaranteed chronological order) const top5Dates = dateKeys .sort((a, b) => new Date(a) - new Date(b)) // Optional: ensure correct time order .slice(0, 5); // Step 3: Initialize our target arrays const labels = []; const data = []; // Step 4: Populate arrays with date strings and corresponding surface temperatures top5Dates.forEach(date => { labels.push(date); // Use optional chaining to safely access nested fields, default to null if missing const surfaceTemp = json[date]?.temperature?.sol ?? null; data.push(surfaceTemp); }); // Check the results in console console.log("Labels array:", labels); console.log("Surface temperature data array:", data); }, error: function(result, statut, error) { console.log(error); } });
Key Explanations
- Filtering Date Keys: The response includes metadata fields like
request_stateandmessage, so we use a regex to filter only keys that match theYYYY-MM-DD HH:MM:SSdate-time format. This ensures we only process the time-stamped data entries. - Sorting (Optional): If you want to be 100% sure the dates are in chronological order (even if the API returns them out of order), we add a sort step using
new Date(a) - new Date(b)to compare timestamps numerically. - Safe Data Extraction: Using optional chaining (
?.) prevents errors if a date entry is missing thetemperatureorsolfield. The nullish coalescing operator (??) sets a defaultnullvalue if those fields are absent, so your arrays stay consistent. - Building Arrays: We loop through the first 5 dates, pushing each date string to
labelsand its corresponding surface temperature todata—exactly the structure you requested.
内容的提问来源于stack exchange,提问作者drag0nfly
相关产品推荐
相关产品推荐

