JavaScript如何将对象插入对象数组:按温度筛选天气数据存入不同数组
问题排查与修复方案
现有代码的核心问题
- 数组声明位置错误:
lstValid被定义在if条件分支内部,每次触发条件都会重新初始化为空数组,之前存入的数据会被完全清空,同时缺少存储temperature > 99的目标数组。 - 逻辑错误:push操作时错误写为
lstValid.push(myObject[i]),myObject本身就是你构造好的单条对象,不需要加索引[i],同时连续调用了两次pushValid(),会导致同一条数据被重复存入数组。 - 异步与作用域问题:for循环中使用
var i存在变量提升,且fetch是异步操作,等到then回调执行时循环早已结束,i的值会指向最后一项,且没有等待所有异步请求完成的逻辑,函数执行结束时无法拿到最终填充完成的数组。
修复后的完整代码
async function calcWeather(){ // 两个分类数组声明在函数顶部、循环外部 const lstLessThan99 = []; // 存储温度<99的对象 const lstGreaterThan99 = []; // 存储温度>99的对象 const api_key = "替换为你自己的openweathermap密钥"; try { // 读取本地JSON数据 const info = await fetch('../json/data.json').then(response => response.json()); // 收集所有天气查询请求的Promise const fetchTasks = Object.values(info).map(async (item) => { const officeBaseInfo = item[0]; const _idOficina = officeBaseInfo.IdOficina; const _nombreOficina = officeBaseInfo.NombreOficinaSN; const _zona = officeBaseInfo.Zona; const _estado = officeBaseInfo.NombreEstado; const lat = officeBaseInfo.latjson; const long = officeBaseInfo.lonjson; const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`; try { const weatherData = await fetch(base).then(res => res.json()); const myObject = { Id_Oficina: _idOficina, Latitud: weatherData.coord.lat, Longitud: weatherData.coord.lon, Ciudad: weatherData.name, Estado: _estado, Zona: _zona, Nombre_Oficina: _nombreOficina, Temperatura: weatherData.main.temp, Descripcion: weatherData.weather[0].description }; // 按温度分类存储 if (myObject.Temperatura < 99) { lstLessThan99.push(myObject); } else if (myObject.Temperatura > 99) { lstGreaterThan99.push(myObject); } } catch (err) { console.error(`坐标${lat},${long}的天气查询失败:`, err); } }); // 等待所有天气查询请求执行完成 await Promise.all(fetchTasks); // 最终结果可在此处使用或返回 console.log('温度小于99的对象列表:', lstLessThan99); console.log('温度大于99的对象列表:', lstGreaterThan99); return { lstLessThan99, lstGreaterThan99 }; } catch (err) { console.error('本地JSON数据读取失败:', err); } };
内容的提问来源于stack exchange,提问作者Martín JF
相关产品推荐
相关产品推荐

