skip to Main Content

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


  1. 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:

        class Product {
            constructor(data) {
                this.image = data.image;
                this.volume = data.volume;
                this.name = data.name;
                this.url = data.url;
                this.price = data.price;
                this.uom = data.uom;
            }
        }
    
    Login or Signup to reply.
  2. You are trying to get data from this.data which will be undefined so you have to use

    constructor(data) {
        this.image = data.image;
        this.volume = data.volume;
        this.name = data.name;
        this.url = data.url;
        this.price = data.price;
        this.uom = data.uom;
    }
    

    For the sake of exmple you can see as:

    class Product {
      constructor(data) {
        this.image = data.image;
        this.volume = data.volume;
        this.name = data.name;
        this.url = data.url;
        this.price = data.price;
        this.uom = data.uom;
      }
    }
    
    let newObj = {
      image: "image",
      volume: "volume",
      name: 'name',
      url: 'url',
      price: 'price',
      uom: 'uom',
    }
    let product = new Product(newObj);
    console.log(product);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search