0

I'm trying to access an element of the first object in an array that is made by pushing instances of another class.

This is the array structure that I'm trying to take values from and I want to get 'price' of each object in the array and put them into an array

arrayOfData[{num: 0, price: 100}, {num: 1, price: 200}, ...]

I tried arrayOfData[0] and some other approaches but still cannot access values. please help me out ...

In createArrayOfData, it gets data from API and then puts needed values into an instance and pushes it to arrayOfData.

In getPrice, this is where is a problem.. I cannot access this.arrayOfData's element even arrayOfData has a collect data.

This is code (it's a simplified version of actual code).

class MainData {
constructor(values, parameter) {
    this.arrayOfData = values;
    // etc..
}

createArrayOfData() {
    let API_Call = `https:XXXXXX.com`;
    const pointerToThis = this;

    fetch(API_Call)
        .then(
            function(response) {
                return response.json();
            }
        )
        .then(
            function(data) {
                let i = 0;
                for (let key in data['All Data']) {
                    const dataInfo = new DataInfo();
                    dataInfo.num = i;
                    dataInfo.price = data['All Data'][key]['price'];
                    pointerToThis.arrayOfData.push(dataInfo);
                }
                i++;
            }
        )
}

getPrice() {
    // To see if it's possible to access a value of price in arrayOfData 
    console.log(this.arrayOfData[0])  // undefined
    console.log(Array.isArray(this.arrayOfData))  // true

    let value = Object.values(this.arrayOfData);
    console.log(value)  // undefined


}

class DataInfo {
    constructor(num, price) {
        this.num = num;
        this.price = price;
        // etc...
    }
}
zityou hanne
  • 41
  • 1
  • 6
  • Unfortunately, this question was closed by someone, but the similar question recommended as an answer of this question was unclear to me... If someone has any advice or comment, that will be huge help ... – zityou hanne Aug 08 '21 at 03:33
  • 1
    The `this` inside of a function is determined by how the function is called. If you do `obj.getPrice()` then the `this` inside your function will be `obj`, as the getPrice() method was called _on_ `obj`. If you do `foo.getPrice()`, then the `this` will be `foo`. If your function is being used as a callback then you're not the one executing it, but rather the function you pass it to, so the `this` won't be what you expect it to be. – Nick Parsons Aug 08 '21 at 03:47

0 Answers0