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

如何在JavaScript中从嵌套JSON/对象数组提取字段生成数组?

嘿,我来帮你搞定这两个问题,咱们一步步拆解:

问题1:如何在JavaScript中从嵌套JSON创建数组?

从嵌套JSON生成数组的核心是先定位到目标数据所在的层级,再根据数据结构(数组/对象)选择合适的方法提取:

情况1:目标数据在嵌套的数组里

如果JSON里已经有数组结构,直接用map就能快速提取字段值到新数组。比如:

// 示例嵌套JSON
const nestedJson = {
  data: {
    weatherItems: [
      { date: "2024-01-01", temp: 12 },
      { date: "2024-01-02", temp: 15 }
    ]
  }
};

// 提取所有temp值到数组
const tempArray = nestedJson.data.weatherItems.map(item => item.temp);
// 结果:[12, 15]

情况2:目标数据在嵌套的对象里

如果嵌套的是对象而非数组,先通过Object.values()把对象转成值数组,再用map提取:

const nestedObjJson = {
  forecast: {
    day1: { dt: 1699999200, temp: 10 },
    day2: { dt: 1700006400, temp: 13 }
  }
};

// 提取所有dt值到数组
const dtArray = Object.values(nestedObjJson.forecast).map(item => item.dt);
// 结果:[1699999200, 1700006400]
问题2:从OpenWeatherMap API数组提取字段到独立数组

针对你的需求,优先推荐用原生JS的map方法——它就是专门为“从原数组生成新数组”设计的,代码简洁易读,性能也很出色。相比之下,for循环可行但代码冗余,each是jQuery的方法,依赖库且没必要用原生支持的方法。

具体实现步骤

首先,OpenWeatherMap的forecast API返回的数据里,天气条目都在list数组中,且temp_min、temp_max是嵌套在main对象里的。假设你已经拿到了API响应数据,代码如下:

// 假设这是你从API获取到的完整响应数据
const weatherResponse = {
  list: [
    { dt: 1699999200, main: { temp_min: 10.5, temp_max: 15.2 } },
    { dt: 1700006400, main: { temp_min: 9.8, temp_max: 14.7 } },
    // 更多天气条目...
  ]
};

// 用map生成三个目标数组
const dtArray = weatherResponse.list.map(item => item.dt);
const tempMinArray = weatherResponse.list.map(item => item.main.temp_min);
const tempMaxArray = weatherResponse.list.map(item => item.main.temp_max);

用for循环的替代方案(兼容旧环境)

如果你需要兼容非常老旧的浏览器(比如IE8及以下),可以用for循环手动实现:

const dtArray = [];
const tempMinArray = [];
const tempMaxArray = [];

const weatherList = weatherResponse.list;
for (let i = 0; i < weatherList.length; i++) {
  const currentItem = weatherList[i];
  dtArray.push(currentItem.dt);
  tempMinArray.push(currentItem.main.temp_min);
  tempMaxArray.push(currentItem.main.temp_max);
}

关于jQuery的each方法

如果你的项目已经引入了jQuery,也可以用$.each,但没必要——原生map更轻量且通用:

const dtArray = [];
$.each(weatherResponse.list, function(index, item) {
  dtArray.push(item.dt);
});
// tempMinArray和tempMaxArray同理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:31:19