Reputation: 339
I have a function that receives object each time it is called, I want to store this object in an Array. But when I push the arrived Object in the Array the previous Object is overwritten. How do I save the Objects without overwriting the previous ones each time am in the function, so that all the objects are printed in the for() function.
drawtimeline(i_items, nom_cal, _hitoService, idcalbuscador) {
var container = document.getElementById('timeLine');
var result: any[] = [];
result.push({ "_id": this.idcalbuscador, "title": nom_cal });
for (let i of result) {
console.log(i);
alert(i);
}
}
Upvotes: 4
Views: 62
Reputation: 10377
Your result
variable is local to the drawtimeline
function. When that function finishes executing, the result
variable is cleared. When that function is called again, a new result
array is allocated, which makes it look like you are clearing the old object stored in the array. Each time you run the function you're printing a separate array containing the single object you just pushed.
The solution is to pull the result
variable out of the function and into the outer scope. The details will depend on if this function is part of a module, a class, or bare. Typically it will look like this:
var result: any[] = [];
drawtimeline(i_items, nom_cal, _hitoService, idcalbuscador) {
var container = document.getElementById('timeLine');
result.push({ "_id": this.idcalbuscador, "title": nom_cal });
for (let i of result) {
console.log(i);
alert(i);
}
}
If you are in a class, you will need to use this.result
Upvotes: 4