You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端调用API获取数据后map数组提取日期温度字段返回undefined如何解决

问题根因

你从接口拿到的JSON结构是嵌套数组:外层是长度为1的数组,内层索引为0的位置才是存储fecha和temperatura字段的目标数组。你直接对外层的data执行map遍历,遍历得到的每个elem实际上是内层的整段数组,自然无法读取到对象属性。

修复方案

你只需要取外层数组的第0项作为遍历的数据源即可,修改后的代码如下:

var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8090/api/grafico/datos/temperatura/medicionAire/2059";
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var data = JSON.parse(this.responseText);
        // 取内层的目标数组
        const targetData = data[0]
        var dateG = targetData.map(function(elem) {
            return elem.fecha;
        });
        var temperatureG = targetData.map(function(elem) {
            return elem.temperatura;
        });
        // 后续可直接将dateG和temperatureG传入图表配置中完成渲染
    }
}

如果担心后续接口返回的嵌套层级不稳定,也可以用flat()方法先把数组拍平再遍历:

const targetData = data.flat()

内容的提问来源于stack exchange,提问作者Luis urrechaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:06:01