Pablo Malynovytch
Pablo Malynovytch

Reputation: 151

How to append data to an object with Javascript

Heres is how I add data to my object:

    let trade = [
       new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol),
   ]

The problem is when I run this:

 console.log(trade[0].price);

It seems that overwrites my object from the beginning.

I add my class code. How i can print the first data from the object

    class RecordStock {

  constructor(price, timestamp, stockquantity, tradetype, stocksymbol) {
    this.price = price;
    this.timestamp = timestamp;
    this.stockquantity = stockquantity;
    this.tradetype = tradetype;
    this.stocksymbol = stocksymbol;
  }
  static recordTrade(){
    console.log(price[0]);
  }
}

Upvotes: 0

Views: 589

Answers (2)

Pablo Malynovytch
Pablo Malynovytch

Reputation: 151

The problem is that inside the function I declare de var every time. I put let trade out of the function

Upvotes: 0

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

I think you are looking to push objects into the trade array. You can achieve this by simply appending to the array.

You can push objects with something like this

Assuming you have a function that adds the RecordStock object. Here is how it could be.

let trade = [];    

trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));

trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));

trade.push(new RecordStock(elem, recordtime, stockquantity, tradetype, stocksymbol));

Now you can access the latest RecordStock you pushed using this trade[trade.length - 1]. trade[0] will always contain the object which you pushed first. This is the usual array functionality.

Upvotes: 1

Related Questions