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

132
Vistas
Group values inside a loop and return it as an object with typescript

New to typescript so not sure how to map values inside a loop. I am running a function which does some logic which returns a number(nothing special). This function will be called in a other function to return 2 values, 1. is a number 2. is a string.

export class matrix {

     public pattern!: {[key: string]: number[]};

     // function will be called in a loop in a different function
     public setPattern(data: number, category: string): void {

         // does some logic here and set row as a value
         const row = 10;// random value of course
 
         this.pattern[category].push(row);// not working of course
     
     } 
}
     
//output should be like this  
{
    "some category": [10,55,4,53,1],
    "more rows": [1,2,8]
} 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

On the first call, the pattern is undefined, it'll not be able to add the key to undefined this.pattern[catergory].

export class matrix {
    public pattern: {[key: string]: number[]} = {};
    public setPattern(data: number, catergory: string): void {
        const row = 10;// random value of course
        this.pattern[catergory].push(row);// not working of course
    } 
}
   
about 4 years ago · Juan Pablo Isaza Denunciar

0

Probably not working when array is not initialized

Add this before pushing new element

if(this.pattern[category] == undefined) this.pattern[category] = []

And then after array is initialized push new element to it

this.pattern[category].push(row);

Also make sure that pattern object is initialized

public pattern!: {[key: string]: number[]}; = {}
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