Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
JavaScript: How can I insert an Object into an Array of Objects?

I have this script that takes data from a JSON with almost 100 data, then uses this data to bring the weather from an API and after that, inserts this data into an object (using a for for creating my 100 objects), I would like to add the objects that have a temperature > 99 in one array and the ones that have a temperature < 99 into another I have tried this way but doesn't seem to work, sorry if it's a super fool mistake that I can't see, thanks for your help!

This is my script:

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())
            }
        });   
    }    
};
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your array is local, so for every object you create new lstValid array with no previous data. The solution is to create the array before fetching the data or before the loop:

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 (...) {
        ...
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

You'll probably be best served by creating the array outside of that call since you're clearing it every run. Then simply add your object. Like Trincot's comment, i'm not sure what exactly you're indexing.

async function calcWeather(){
    var lstValid = [];
    ....
   
    if (myObject.Temperatura < 99){
        lstValid[someindex] = myObject;
    }
    else{
        lstNotValid[someOtherIndex] = myObject;
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda