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

130
Views
¿Cómo recorrer el objeto de cadenas con fechas en mecanografiado?

Tengo un objeto, las claves son fechas, antes del punto son meses, después son años:

 const dataObj = { '01.2015': 0.01, '02.2015': 0.10, '03.2015': 0.05, '04.2015': 0.25, // ... }

la función toma dos fechas y devuelve una matriz con objetos que contienen valores de dataObj

 interface Point { date: string; value: number; } type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'; type Day = `${Digit}${Digit}`; type Month = | '01' | '02' // ... | '11' | '12'; type Year = '2015' | '2016' | '2017'; type DateString = `${Day}.${Month}.${Year}`; type MonthDateString = `${Month}.${Year}`; function count(firstDate: DateString, secondDate: DateString): Point[] { const result: Point[] = []; let currentDate = firstDate.slice(3) as MonthDateString; // loop through dataObj and push in result return result // [{date: '01.2015', value: 0.01}, {...}, ...] }

¿Cómo recorrer dataObj? Traté de bucle

 for(let i = currentDate; i !== secondDate.slice(3); )

pero no tengo idea de qué hacer con la expresión final, cómo actualizar la variable del contador, pasar la siguiente clave (cadena con fecha) de dataObj.

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

0

Algunos ejemplos a continuación:

 for (let key in dataObj) { console.log(key, dataObj[key]); } for (let [key, value] of Object.entries(dataObj)) { console.log(key, value); }

Si desea tener y actualizar la variable de contador:

 let keys = Object.keys(dataObj); for (let i = 0; i < keys.length; i++) { console.log(i, keys[i], dataObj[keys[i]]); }
about 4 years ago · Juan Pablo Isaza Report

0

Existe cierta confusión con respecto al resultado esperado. El count de funciones debe devolver una matriz de Point , que es una matriz de objetos donde cada objeto tiene dos accesorios, a saber, date (una cadena) y value (número, coma flotante por comentarios en línea en el código).

Se supone que el OP requiere encontrar pares clave-valor en dataObj de modo que la clave (es decir, mes-año) esté entre firstDate y secondDate (que son parámetros para count la función).

Según esta suposición, el siguiente código puede lograr el objetivo deseado (generar una matriz de elementos Point ).

 const isGreaterOrEqual = (dtOne: MonthDateString, dtTwo: MonthDateString) : Boolean => { const getYear = (dt: MonthDateString) : string => dt.slice(3); const getMonth = (dt: MonthDateString) : string => dt.substring(0, 2); return ((getYear(dtOne) > getYear(dtTwo)) || (getYear(dtOne) === getYear(dtTwo) && getMonth(dtOne) >= getMonth(dtTwo) ) ); }; function count(firstDate: DateString, secondDate: DateString): Point[] { let beginDate = firstDate.slice(3) as MonthDateString; let endDate = secondDate.slice(3) as MonthDateString; return ( Object.entries(dataObj) .filter(([k, v]) => isGreaterOrEqual(k as MonthDateString, beginDate) && isGreaterOrEqual(endDate, k as MonthDateString)) .map(([k, v]) => ({ date: k, value: v} as Point)) ); }; console.log(count( "01.01.2015" as DateString, "01.02.2015" as DateString));

TS Playground: enlace aquí

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!