0

I use TypeScript for create array:

private menuItems: Menu[][];

After in loop I try to fill this like:

this.menuItems[role].push(this.menu[i]);

In result I want to get the following:

[1 : [{obj}, {obj}], 2: [{obj}, {obj}], 3: [{obj}, {obj}]]

What I do wrong?

Full code is:

public getMenuByRole(role: number): Menu[][] {
    for ( let i = 0; i < this.menu.length; i++ ) {
      if (this.menu[i].role === role && this.menu[i].avaliable) {
          this.getTranslateMenuItem(this.menu[i].title).subscribe((translation: string) => {
            this.menu[i].title = translation;
            this.menuItems[role].push(this.menu[i]);
          });
      }
    }
    return this.menuItems;
  }

Problem is that I try to add new objecti in array by custom key array, that is not exist

I tried also this:

const obj = {};
const arr = Array();

The in loop:

arr.push(this.menu[i]);
obj[role].push(arr);
10
  • please, show some relative code you have written for it and also error, if you are getting one. Commented Sep 9, 2017 at 19:43
  • This is full code. I initialize array [][], and tried to fill it Commented Sep 9, 2017 at 19:44
  • what does this.menu contains? Maybe you can show some sample data. Commented Sep 9, 2017 at 19:44
  • I guess, that it should be object of array like as: {1 : [{}. {}], 2: [{}, {}] } Commented Sep 9, 2017 at 19:46
  • 1
    Aside: I might invert your logic such that the menu item knows what roles it can be shown to. Each menu item could have children: menuItem[]. This way you can build your menu graph without a complex array. Commented Sep 9, 2017 at 19:54

1 Answer 1

1

You just need to create an array inside an array to get a two dimensional array. I would use an object though. Hope this is what you are looking for

class A {
 private menu: [];

 constructor(){

 this.menu = new Array();
 for(let i = 0; i< 10; i++){
    let menuItem = new Array();
    menuItem.push(new B(i));
    menuItem.push(new B(i+1));
    this.menu.push(menuItem);
  }
  console.log(this.menu);
 }
}

class B {

 constructor(public x: int){
 }
}

new A();

https://jsfiddle.net/64r04pp2/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.