The items in my array have been replaced with new objects

I am facing an issue with storing objects in an array within a function. Every time the function is called, a new object is received and I want to add it to the existing array without overwriting the previous objects. This way, all the objects can be accessed and printed using a for loop.

 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);
    }
}

Answer №1

The result variable is specific to the drawtimeline function and gets cleared once the function execution is complete. Subsequently, each time the function is called, a new result array is created, giving the impression that the previous object stored has been deleted. This leads to printing separate arrays with only one object each time the function runs.

To resolve this issue, move the result variable outside of the function scope and into the broader scope. The implementation will differ based on whether the function is within a module, class, or standalone. Typically, it will involve:

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);
    }
}

In case you are working within a class, use this.result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging retrieved API data to generate numerous components

Hey there! I'm new to JavaScript and I'm working on creating a todo list with fake ToDos from jsonplaceholder using Fetch. My goal is to fetch five different ToDos and display them in separate list items within my list. However, I'm encounte ...

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

The path aligns with the route, yet the component designated for that route fails to render

I wrote a React component named Workout that looks like this: const Workout = props => { console.log(props); return ( <div> <h1>hello</h1> </div> ); }; export default Workout; Next, I imported this componen ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

Angular 7 - Personalized Name for Formbuilder's Dynamic Form

Currently, I am developing a form builder with Angular: return this.fb.group( { myaccount: [ '', [Validators.required]] } ); When an error message is thrown for an element, I iterate through the form controls and disp ...

What is the best way to create a floating navigation bar that appears when I tap on an icon?

As a beginner in the realm of React, I recently explored a tutorial on creating a navigation bar. Following the guidance, I successfully implemented a sidebar-style navbar that appears when the menu icon is clicked for smaller screen sizes. To hide it, I u ...

The serverless functions in Next.Js only seem to work after being pinged

I am dealing with an endpoint in my project that receives messages from a WhatsApp webhook. This endpoint then makes an asynchronous call to another endpoint and responds with a 200 status back to the WhatsApp webhook. While this process works smoothly an ...

Using Angular and RxJS to trigger an email once all values have been emitted successfully

saveData$ is an observable that emits multiple values. I am looking to optimize the email sending process by only sending one email once all values have been successfully emitted. Currently, an email is sent for each individual value that is emitted, whi ...

Guide on resetting a value in ajax search to enable pagination of results

I've run into an issue with a "load more button". Each time I perform a new search, I want to display the second page of results and subsequent pages. However, the value I'm using to determine the current page keeps increasing continuously. I nee ...

What is the process for utilizing global packages when running `ng serve`?

After successfully using npm to download and install packages globally for my project, I encountered an error when running ng serve --port 34000: C:\app>ng serve --port 34000 Node packages may not be installed. Try installing with 'npm install ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Guide on how to programmatically activate a disabled button that has been set in the layout

As someone who is new to the world of Android, I am currently learning how to work with spinners, buttons, and their attributes. In my app, I have 4 spinners where each spinner's values are dependent on the selection made in the previous spinner. Bel ...

Is it possible to use JavaScript to clear a field that was generated by Yii CRUD?

Issue with Yii's GRUD field generated and Firefox HTML: <?= $form->field($model, 'productId')->textInput(['maxlength' => true]) ?> Comparison of PHP generated code to Firefox HTML: <input id="taolistforcreate-p ...

When processing UTF-8, REST only acknowledges English characters and ignores any other characters

When sending an AJAX request in UTF8 to a server that uses REST, any part that contains non-English characters is disregarded. I am working with Java on the server side with REST, and the client sends AJAX requests in UTF8 that may include Hebrew words. ...

skipSelector is not recognized

While attempting to create a new component in Angular, I encountered the following error: ng g c contact-us Your global Angular CLI version (8.1.1) is greater than your local version (7.1.4). The local Angular CLI version is used. To disable this warning ...

Create forms that can be dragged and drop to your desired location, with the ability to

I am trying to implement drag and drop functionality to this https://stackblitz.com/edit/angular-dynamic-survey-creation-golkhg project and save the data to a JSON file. I have been using Angular CDK but I am facing an issue with the following function: o ...

Adding a key-value pair to an array using the array_push() function

I have a pre-existing array and I need to add a new value to it. My attempts to use array_push() have been unsuccessful. This is the code I've tried: $data = array( "dog" => "cat" ); array_push($data['cat'], 'wagon'); W ...

I am having difficulty accessing the dataset on my flashcard while working with React/Next JS

I'm currently developing a Flashcard app that focuses on English and Japanese vocabulary, including a simple matching game. My goal is to link the two cards using a dataset value in order to determine if they match or not. When I click on a flashcar ...

Trouble Ensuring First Radio Button Is Checked in Angular 6

I'm working on setting the first radio button in a group to be checked by default. Within my application, I have 6 tabs each containing a set of scales that need to be displayed as radio buttons. The goal is to have the first button in each tab check ...

Surprising symbol encountered: JavaScript, Node.js, and MongoDB

                 I am facing an unexpected identifier error while running the code below when trying to check if the documents' state has changed. Despite exhausting my Google search and looking for documentation on MongoDB, I am yet to find ...