I’m trying to create a new object. I’m passing a dictionary to the constructor, but I keep getting an Uncaught TypeError: Cannot read properties of undefined (reading 'image')
class Product {
constructor(data) {
this.image = this.data.image;
this.volume = this.data.volume;
this.name = this.data.name;
this.url = this.data.url;
this.price = this.data.price;
this.uom = this.data.uom;
}
}
for (let i = 0; i < rootNodes.length; i++) {
image = rootNodes[i].querySelector(".product-img").getAttribute("src");
volume = rootNodes[i].querySelector(".co-product__volume").textContent;
name = rootNodes[i].querySelector(".co-product__anchor").textContent;
url = rootNodes[i].querySelector(".co-product__anchor").href;
price = rootNodes[i].querySelector(".co-product__price").childNodes[1];
uom = rootNodes[i].querySelector(".co-product__price-per-uom").textContent;
var product = new Product({
image: image,
volume: volume,
name: name,
url: url,
price: price,
uom: uom
});
products.push(product);
}
I can’t see what I’m doing wrong here, can someone please explain? Thank you.
I haven’t tried anything, yet.
2
Answers
The issue in your code lies in how you are accessing the properties of the data object within the Product constructor. Instead of accessing the properties directly, you are trying to access them from an undefined variable this.data. To fix this, you should use data directly without the this keyword. Here’s the corrected code:
You are trying to get data from
this.data
which will beundefined
so you have to useFor the sake of exmple you can see as: