Home > Software design >  Problem to initialize 2D Array in Angular
Problem to initialize 2D Array in Angular

Time:09-16

I have problems to initialize the "categorizedProductsPath" array, both approaches do not work, where´s the failure?

      // let categorizedProductsPath: number[][] = [];
      let categorizedProductsPath = new Array<number[]>(categorizedProducts.length);
      for (let k = 0; k < categorizedProducts.length; k  ) {
        const categorizedProduct = categorizedProducts[k];
        const categoryOfCategorizedProduct = await this.getCategoryToProduct( categorizedProduct.google_product_category);

        let currentParentId = categoryOfCategorizedProduct.parentId;
        while (currentParentId !== 0) {
          const parentCategory = await this.getCategoryToProduct(currentParentId);
          currentParentId = parentCategory.id;
          categorizedProductsPath[categorizedProduct.id].push(parentCategory.id); //***
        }
      }

The error (TypeError: Cannot read properties of undefined (reading 'push')) comes here ***:

categorizedProductsPath[categorizedProduct.id].push(parentCategory.id);

Regards

CodePudding user response:

You want categorizedProductsPath to be a nested array of number[][]. But currently it is an empty array, you didn’t initialize it correctly.

const arr = new Array(3) will just give you an array of three undefined. If you want an array of three other empty arrays, like [[], [], []], this is what you gonna do:

const arr = new Array(3).fill(0).map(() => [])

CodePudding user response:

You created the outer array, but did not create the inner array. You have to do categorizedProductsPath[categorizedProduct.id] = [] first before you can push to it;

Note that this may create a sparse array if categorizedProduct.id are not consecutive integers starting from zero. It's still ok. But in case the order of categorizedProduct.id has no meaning, you may consider just using an object instead of an array.

  • Related