"Displaying only the most recent item added to a Typescript array using

After retrieving a list from my API, the data looks like this:

{
  "content": [
    {
      "trainingClassId": 1,
      "examCode": "my exam 1",
      "address": {
        "addressId": 1,
        "addressValue": "abc 1213"
      },
      "description": "only test",
      "classId": null,
      "startDate": 1511110800000,
      "endDate": 1513702800000,
     "examDate": 1511542800000

    },
    {
      "trainingClassId": 2,
      "examCode": "my exam 2",
      "address": {
        "addressId": 1,
        "addressValue": "abc 1213"
      },
      "description": "only test",
      "classId": null,
      "startDate": 1511110800000,
      "endDate": 1513702800000,
     "examDate": 1511542800000
    }
  ],
  "last": true,
  "totalElements": 2,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 2
}

To convert long timestamps to date format, I've created a data binding object like this:

export class myApp {
    id: number;
    classId: string;
    trainingDate: string;
    examDate: string;

}

In my TypeScript file:

listData = new Array();

  app_unit:myApp= new myApp();
  listApp:any[];

ngOnInit() {
    this.getAllTrainingClass();

  }
 async getAllTrainingClass(): Promise<void>{
     await this.traningClassService.getdata().then(data =>this.listApp = data);

     for(let ls of this.listApp){


        this.app_unit.classId = ls.classId;
        this.app_unit.examDate=this.convertTimestampToDate(ls.examDate);
        this.app_unit.trainingDate=this.convertTimestampToDate(ls.startDate) +'-'+this.convertTimestampToDate(ls.endDate) ;

       this.listData.push(this.app_unit);


     }

The console log displays 2 items, but they are both the latest item, shown here:

{0:myApp id:2 classId:null examDate:"05/01/2018" trainingDate:"05/11/2017-31/12/2017" }, {1:myApp id:2 classId:null examDate:"05/01/2018" trainingDate:"05/11/2017-31/12/2017"}

Please provide me with some advice on this situation.

Answer №1

The issue arises from the fact that "this.app_unit" is referencing the same memory location, causing you to add the same object to the array with all references pointing to that single memory location.

To resolve this problem, place:

var app_unit:myApp= new myApp(); 

within the for loop. This way, a new instance of the object is generated with each iteration.

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

Cover a cube with a material using Three.js

After following the tutorial on creating a Cube with a texture, I encountered an issue where the texture repeated on every face of the cube. I am seeking a solution to use a single texture that 'wraps' around the cube. Is there a way to achieve t ...

Inserting a Specific Iframe into a Designated Location in HTML with the Help of Jquery

Currently, I am encountering an issue with placing a dynamically created iframe inside a specific section of my webpage. The iframe is supposed to be contained within a div element named "maps", but instead it is appearing at the bottom of the page.This ma ...

The challenge of migrating from Angular2 Rc4 to Rc5: dealing with traceur bug

Encountering 'traceur 404' error in console during the migration process of my angular cli project from Rc4 to Rc5 https://i.stack.imgur.com/j4SU1.png Referenced this article for guidance: app.module.ts import {NgModule} from '@angu ...

What causes the maximum update depth exceeded error in React when trying to set data to the context?

When building my React project, I implemented a context to share the selected currency across components. While the context functionality is working well, I encountered a small issue regarding setting a default currency. At the start of the web applicati ...

Exploring the Power of Angular 2 with NgRx

Seeking advice from NgRx users. I have noticed a discrepancy between the official documentation and various articles and tutorials regarding whether to use classes for actions, reducers, etc. Which approach is considered more effective? Official documenta ...

What is the reason for importing this JS module in TypeScript with a "default" property?

This particular code snippet comes from a specialized i18n module, situated within ./esm/locale/en.js: import cardinal from '../rules/rule5'; import ordinal from '../rules/rule42'; var pluralRule = { ordinal: ordinal, cardinal: card ...

Handling Errors with Symfony 5 JSON Responses and VueJS Using Axios for Customized Error Messages

I need to show a personalized error message when my JSON response throws an error. Some of my services trigger an error like this: if (count($recipients) === 0) { throw new TransportException($this->carrierService::ERROR_NO_MAIL_ADDRESSES); } The ...

Using `useState` within a `while` loop can result in

I'm working on creating a Blackjack game using React. In the game, a bot starts with 2 cards. When the user stands and the bot's card value is less than 17, it should draw an additional card. However, this leads to an infinite loop in my code: ...

Executing window.open from Html.Actionlink in ASP.NET MVC 4

Here is the code block I am working with: @foreach (System.Data.DataRow drEquipment in Model.EquipmentList.Rows) { <tr> <td valign="top">@drEquipment["ColumnName"]<br /></td> <td valign="to ...

The problem with the pathLength property is causing my path animation to malfunction

I'm struggling to animate SVG graphics and haven't been able to find much information on this topic online. Recently, I attempted to animate an SVG using framer-motion in a React component. The animation configuration I used is as follows: const ...

Bring in NPM package that relies on another module

Recently transitioning to Meteor 1.3 with npm module support, I've encountered the following issue: TypeError: Cannot set property 'tip' of undefined Below is the relevant code snippet in myFile.js: import d3 from 'd3'; import d ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

"Enhance your Vue 3 project with TypeScript and take advantage of smart template suggestions

Is it feasible to enable autocompletion/suggestions in the template section of a Single File Component (SFC) when using VS Code with Vue 3 and Typescript, particularly for component props? For instance, consider a basic component named UserComponent: < ...

How does the scope of functions included in files differ between Javascript and PHP?

Last month, I inquired about a PHP issue involving calling a function in one include file that is defined in a later include file. This problem came up during the conversion of an ASP site to PHP, and now it's resurfacing. It seems like Javascript and ...

When using Express.static, the website functions properly but an error message "GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)" is displayed

Having an issue with express.static. My project is a basic portfolio website that includes a form for sending emails. I referred to this tutorial on Nodemailer: Tutorial Nodemailer Github The problem arises within my index.html file (this example applies ...

The Sharp Promise<Buffer>[] lacks some essential properties compared to the type Promise<File | File[]>: specifically, then, catch, finally, and [Symbol.toStringTag]

I wrote a script to verify and convert images as they pass through. Utilizing resources from nestjs, magic-bytes.js, and Sharp. However, I encountered the following error: Type 'Promise<Buffer>[]' is missing the following properties from ...

Angular HTTP Post request not functioning as expected

I'm trying to send a post request in this manner (the correct baseURL is set, and the path /api/backend/valuePairs exists on the server). sendValues(valuepairList:{x:number;fx:number}[]): Observable<boolean> { const headers = new Heade ...

Is there a way to use JavaScript to retrieve a list of files that were loaded by the browser during the last request

I'm just starting out in the world of JavaScript and I have a query: is there a method to retrieve a list of files that were loaded by the browser during the last request? To clarify, when a browser loads a webpage, it not only downloads the HTML fil ...