skip to Main Content

I keep getting typeError Cannot read properties of undefined from this code. The weird thing is yesterday, it was working perfectly.

here is the code:

const products = [{
        id: "e43638ce-6aa0-4b85-b27f-e1d07eb678c6",
        image: "imgs/products/athletic-cotton-socks-6-pairs.jpg",
        name: "Black and Gray Athletic Cotton Socks - 6 Pairs",
        rating: {
            stars: 4.5,
            count: 87
        },
        priceCents: 1090,
    },
    {
        id: "15b6fc6f-327a-4ec4-896f-486349e85a3d",
        image: "imgs/products/intermediate-composite-basketball.jpg",
        name: "Intermediate Size Basketball",
        rating: {
            stars: 4,
            count: 127
        },
        priceCents: 2095
    }
];



const cart = [{
    productId: "156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh",
    quantity: 2,
}];


let matchingProduct;

cart.forEach((cartItem) => {
  let productId = cartItem.productId;

  products.forEach((product) => {


      if (product.id === productId) {
          matchingProduct = product
      }

  });

  console.log(matchingProduct)

Could you please help me to understand why this is happening.

Thank you.

I am confused and tried to identify the error. the only thing that I found is that for some reasons the if statement doesn’t seem to work.

2

Answers


  1. With your code, you try to check if 156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh from const cart is in const products. 156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh (cart[0].productId) is neither equal to products[0].id or products[1].id. Subsequently, no value is set tolet matchingProduct, which gives you undefined as output.

    Login or Signup to reply.
    1. Check Product IDs: Make sure that productId in your cart array matches an id in your products array. Even small typos or differences in IDs could cause this error.
    // Check for matching product IDs
    let matchingProduct = null;
    
    1. Console Logging: Add some console logs to assist with debugging. Log both productId and product.id to see which values are being compared.
    // Logging for debugging
    cart.forEach((cartItem) => {
      let productId = cartItem.productId;
    
      products.forEach((product) => {
        console.log("Comparing:", productId, product.id);
    
        if (product.id === productId) {
          matchingProduct = product;
        }
      });
    });
    
    console.log("Matching Product:", matchingProduct);
    

    Now, your code is formatted for use on Stack Overflow, and it will appear as if you wrote it yourself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search