【问题标题】:JavaScript: How can I insert an Object into an Array of Objects?JavaScript:如何将对象插入到对象数组中?
【发布时间】:2021-10-21 16:49:35
【问题描述】:

我有这个脚本,它从包含近 100 个数据的 JSON 中获取数据,然后使用这些数据从 API 中获取天气,然后将这些数据插入到一个对象中(使用 for 创建我的 100 个对象),我想将具有temperature > 99 的对象添加到一个数组中,将具有temperature < 99 的对象添加到另一个数组中我看不到,谢谢你的帮助!

这是我的脚本:

async function calcWeather(){ 
    const info = await fetch('../json/data.json')
    .then(function(response) {
        return response.json()
    }); 
    for (var i in info) {
        const _idOficina = info[i][0].IdOficina
        const _nombreOficina = info[i][0].NombreOficinaSN
        const _zona = info[i][0].Zona
        const _estado = info[i][0].NombreEstado
        const lat = info[i][0].latjson 
        const long = info[i][0].lonjson 
        const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`
        fetch(base)
        .then((responses) => {
            return responses.json()
        })
        .then((data) => {
            // console.log(data)
            var myObject = { 
                Id_Oficina: _idOficina,  
                Latitud: data.coord.lat,
                Longitud: data.coord.lon,
                Ciudad: data.name, 
                Estado: _estado,
                Zona: _zona,
                Nombre_Oficina: _nombreOficina,
                Temperatura: data.main.temp, 
                Descripcion: data.weather[0].description
            };  
            // validation
            if (myObject.Temperatura < 99){
                var lstValid = [];
                function pushValid(){
                    lstValid.push(myObject[i]);
                }
                pushValid();
                console.log(pushValid())
            }
        });   
    }    
};

【问题讨论】:

  • 你认为myObject[i]指的是什么?此外,每次你发现一个低温物体时,你将lstValid重置为一个空数组,丢失你已经推入的任何东西。
  • 我该如何解决?
  • 你能回答我的第一个问题吗?
  • 对不起,伙计,myObject[i] 指的是我正在使用我拥有的数据创建的对象,但该对象不需要[i] 我还没有看到它
  • 您应该考虑将每个信息映射到代表获取该信息的天气的承诺,然后等待所有承诺,然后将所有结果映射到您的自定义对象,然后过滤生成的自定义对象按温度范围(两次:= 99 一次)。

标签: javascript arrays json object


【解决方案1】:

您的数组是本地的,因此您为每个对象创建新的lstValid 数组,而没有以前的数据。解决方案是在获取数据之前或在循环之前创建数组:

async function calcWeather(){
    var lstValid = []; // HERE
    const info = await fetch('../json/data.json')
    .then(function(response) {
        return response.json()
    }); 
    var lstValid = []; // OR HERE (ONLY ONE OF THEM)
   for (...) {
        ...
    }

【讨论】:

  • 我犯了一个可怕的错误,谢谢
【解决方案2】:

您可能最好通过在该调用之外创建数组来获得最佳服务,因为您每次运行都会清除它。然后只需添加您的对象。就像 Trincot 的评论一样,我不确定您到底在索引什么。

async function calcWeather(){
    var lstValid = [];
    ....
   
    if (myObject.Temperatura < 99){
        lstValid[someindex] = myObject;
    }
    else{
        lstNotValid[someOtherIndex] = myObject;
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多