I'm writing code in JavaScript running on nodejs.
The intent is to capture a trading candles worth of data into an object, then push that object into an array, where I can store and reference multiple candle's worth of data. I'm getting stuck on the simplest of first steps (not a pro).
My simplified code is below. I've removed a lot just to make the example without adding more code than necessary.
var bitcoinCandleHistoryArray = [];
var candleObject = {
open: 0,
high: 0,
low: 0,
close: 0,
volume: 0
};
candleObject.open = 100;
candleObject.high = 100;
candleObject.low = 100;
candleObject.close = 100;
candleObject.volume = 10000;
bitcoinCandleHistoryArray.push(candleObject);
candleObject.open = 0;
candleObject.high = 0;
candleObject.low = 0;
candleObject.close = 0;
candleObject.volume = 0;
bitcoinCandleHistoryArray.push(candleObject);
Essentially, if I update my candleObject, then push the first candleObject values to the array, I get a an array with my first candle in it. Then if I update my candle object, prior to pushing a second candle in, the array's first candle entry will update.....before I've pushed it....
So if I set candleObject.open = 0, then [bitcoinCandleHistoryArray[0].open also immediately becomes 0, without a push.
I was expecting the CandleObject's values to be independent of any values in my array.
CodePudding user response:
I was expecting the CandleObject's values to be independent of any values in my array.
They are not. After you push candleObject
into the array, the variable candleObject
still references the same object that is now also in the array (referenced by the array).
For the data to be independent, you need to create a new object for each element in the array.
You could either do so by inlining the creation of the objects like this:
var bitcoinCandleHistoryArray = [];
bitcoinCandleHistoryArray.push({
open: 0,
high: 0,
low: 0,
close: 0,
volume: 0
});
bitcoinCandleHistoryArray.push({
open: 100,
high: 100,
low: 100,
close: 100,
volume: 10000
});
Or, in case you want to stay closer to your original example, you can look into Object.assign
, which allows you do make a copy of candleObject
that can then be pushed into the array.