Skip to content
Advertisement

Uncaught TypeError: Cannot read properties of undefined while looping objects

So , I have 2 objects that are made of products , the main and the secondary , i have made a loop that searches in the main , and if it does not find the product , it deletes is from the secondary, Even though , with 10 products it worked, now that i have 1470 products the loop stops on the 4th repeat and says << Uncaught TypeError: Cannot read properties of undefined (reading ‘name’) >> , Here is the code

JavaScript

when i loop 10 products it works fine every time . Do i need to do something else now that the products are significantly more?

Edit

So the objects are made like this and i take the from woocommerce

[ { “id”: 67537, “name”: “test 10”, “slug”: “”, “type”: “simple”, “status”: “draft”, “featured”: false, “catalog_visibility”: “visible”, “description”: “

allagi

n”, “short_description”: “”, “sku”: “1230975071-1-1-1-1-1-1-1-1-1”, “price”: “123122”, “regular_price”: “123123”, “sale_price”: “123122” } { “id”: 67536, “name”: “test 9”, “slug”: “”, “type”: “simple”, “status”: “draft”, “featured”: false, “catalog_visibility”: “visible”, “description”: “

allagi

n”, “short_description”: “”, “sku”: “1230975071-2”, “price”: “123122”, “regular_price”: “123123”, “sale_price”: “123122”}]

Here is a picture

both objects are from woo

Advertisement

Answer

The problem is – you are running out of the bounds of you product array. It’s caused by:

  1. You have 1470 products, but iterating over 1550 for (i = 0; i < 1550; i++). Can be fixed with for (i = 0; i < secondary.length; i++)
  2. No additional checks do we have next element or not in while loop

So I suppose fixed and optimized version of code may look like this:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement