user759235
user759235

Reputation: 2207

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]
} 

Upvotes: 0

Views: 207

Answers (2)

Bane2000
Bane2000

Reputation: 187

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[]}; = {}

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 10081

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
    } 
}
   

Upvotes: 1

Related Questions