0

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

2 Answers 2

1

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(() => [])
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.