Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda