Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
Javascript: el objeto deja de ser reconocido como un objeto definido

Estoy trabajando en una aplicación meteorológica que extrae algunos datos.

A la mitad deja de reconocer uno de los objetos como un objeto y arroja: Uncaught (in promise) TypeError: data is undefined

Ahora, esto parece estar relacionado con mi if anidado. Si elimino las líneas indicadas, funciona bien y la promesa se completa. De lo contrario arroja el error.

Este es el script que dejó de funcionar.

 async function processHourly(hourly){ let data = await pullData(hourly); // Pull data is just fetch.then(return res.json) data = data.properties; let dataHours = data.periods; // Exception thrown on data, here. let weatherObj = new Array; let objNum=0; let avgTemp; let dateCheck; for(x in dataHours) { // Grab the day's hours //console.log(dataHours[x].startTime) if(dataHours[x].startTime.slice(8,10)!=dateCheck){ weatherObj[objNum] = new Weather weatherObj[objNum].Year = dataHours[x].startTime.slice(0,4) // takes 0-3 weatherObj[objNum].Month = dataHours[x].startTime.slice(5,7)-1 // takes 5 and 6 weatherObj[objNum].Date = dataHours[x].startTime.slice(8,10) // takes 8 and 9 weatherObj[objNum].getDay(); objNum++; typeof(weatherObj[objNum]) // If these are removed if(dataHours[x].startTime.slice(11,13)>=12) // Then it processes data as { // a completed promise. weatherObj[objNum].IsNight = true; // } // } dateCheck=dataHours[x].startTime.slice(8,10); } console.log(dataHours) for(x in weatherObj){ weatherObj[x].setDateObj() console.log(x,weatherObj[x].dateObj) } }

¿Alguien sabe por qué es eso? Siento que me estoy perdiendo algo bastante simple. ¿No parece que las variables afecten el alcance de los datos?

editar -1/7/22, función pullData aclarada

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El proyecto

Esta es una aplicación meteorológica simple que se reproducirá en una pantalla en bucle para la comunidad. Extrae datos de los pronósticos por hora de la API de weather.gov y procesa algunos datos. Este es el proceso que se está realizando.

El esquema json de data se puede encontrar aquí


Si bien no estoy completamente seguro de por qué, parece que usar = para asignar el valor estaba causando problemas en lugar de usar funciones de matriz.

El siguiente es un acortamiento del resaltado original donde radica mi problema.

Código roto

 if(dataHours[x].startTime.slice(8,10)!=dateCheck){ weatherObj[objNum] = new Weather /** THIS IS OUR PROBLEM CHILD **/ ... ... if(dataHours[x].startTime.slice(11,13)>=12) // Then it processes data as { // a completed promise. weatherObj[objNum].IsNight = true; // } // }

correcciones

En su lugar, usé .push() para asignar el nuevo objeto meteorológico al lugar. Seguimiento mediante la asignación de objNum para igualar el índice del objeto meteorológico actual a medida que itera a través de la creación.

Además, agregué claves para la hora del pronóstico para su posterior procesamiento y promedio.

La corrección con la que terminé es la siguiente.

Código de trabajo

 let checkable; //Good for testing async function processHourly(hourly) { let data = await pullData(hourly); data = data.properties; let dataHours = data.periods; let weatherObj = new Array; let objNum=0; let dateCheck=-1; // forces first pass to always create a new weather console.log(dataHours[0]) // To double check variable names for(x in dataHours){ // Start creating objects if( dataHours[x].startTime.slice(8,10)!=dateCheck){ weatherObj.push(new Weather); dateCheck = dataHours[x].startTime.slice(8,10); objNum = weatherObj.length-1 } weatherObj[objNum].hourTemp.push({ hour : dataHours[x].startTime.slice(11,13), temp : dataHours[x].temperature }); weatherObj[objNum].hourForecast.push({ hour : dataHours[x].startTime.slice(11,13), forecast : dataHours[x].shortForecast }) weatherObj[objNum].hourWindDir.push({ hour : dataHours[x].startTime.slice(11,13), direction : dataHours[x].windDirection }) weatherObj[objNum].hourWindspeed.push({ hour : dataHours[x].startTime.slice(11,13), speed : dataHours[x].windSpeed.slice(0,-4) }) } checkable = weatherObj }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!