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
With your code, you try to check if
156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh
fromconst cart
is inconst products
.156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh
(cart[0].productId
) is neither equal toproducts[0].id
orproducts[1].id
. Subsequently, no value is set tolet matchingProduct
, which gives youundefined
as output.productId
in yourcart
array matches anid
in yourproducts
array. Even small typos or differences in IDs could cause this error.productId
andproduct.id
to see which values are being compared.Now, your code is formatted for use on Stack Overflow, and it will appear as if you wrote it yourself.