None
None

Reputation: 9247

How to dynamically create n arrays?

I have this object:

public obj: any = { row1: [], row2: [], total: [], sumTotal: 0, count: 0 };

How can i create n empty arrays ?

Im trying something like this but its not working:

if (this.i === 0) { this.obj.row['_' + this.row] = new Array(); }

Any suggestion?

Upvotes: 1

Views: 71

Answers (2)

ahmeticat
ahmeticat

Reputation: 1939

You can create object like this

let length = 15;// Whatever you want
for(let i=0;i<length;i++){
  if(this.obj['row'+i] === undefined){
    this.obj['row'+i] = [];
  }
}

Upvotes: 0

SparkFountain
SparkFountain

Reputation: 2270

if (this.i === 0) { this.obj.row['_' + this.row] = new Array(); }

You have to create the row property a little different. The way you typed it would try to access this.obj.row, in other words the row property of the obj property of this. And on that object, you would try to access the property '_' + this.row.

Below you find the correct solution. Just include the word row and omit the underscore:

if (this.i === 0) { this.obj['row' + this.row] = new Array(); }

Upvotes: 1

Related Questions