I’m kind of new to Javascript. Any help or suggestion regarding below problem is highly appreciated.
I wanted to create an array which inturns contains list of objects. Given below code summarizes my problem
{
var Instrument = {};
var InstrumentArray = new Array;
var array = new Array;
array[0] ="XYZ0";
array[1] ="XYZ1";
.
.
.
array[n] ="XYZn" ;
data1['Name'] = "X";
data1['TypeString'] = "WatchList";
data1['FileTypeString'] = "XLS";
for (var i = 0; i < array.length; i++) {
Instrument['Symbol'] = array[i];
InstrumentArray.push(Instrument);
}
for(var j =0; j< InstrumentArray.length;j++)
{
console.log(InstrumentArray[j]);
}
}
When I look into the output via console.log it displays me the correct number of values but
the Symbol: value it displays is the last one that I have entered in this case “XYZn”.
I know that the last value overrides the Symbol Object but is their any way I can get all the values stored.
Thanks in Advance
It’s because each element in the array
InstrumentArrayis a reference to same objectInstrument, and you keep changing the properties of that one object. There are many things to improve in your code, but the short answer is to createInstrumentinside the loop.