Create a dynamic function that adds a new property to every object in an array, generating unique values for

On my server, I have a paymentList JSON that includes date and time. Utilizing moment.js, I am attempting to create a new property called paymentTime to store the time data, but it seems to not update as expected.

  this.paymentList.forEach(element => {
                          console.log(moment(element.paymentDate).format("hh:mm A"));
                           console.log(moment(element.paymentDate).format("DD-MMMM-YYYY"));
                           element.paymentTime = moment(element.paymentDate).format("hh:mm A");
                           element.paymentDate = moment(element.paymentDate).format("DD-MMMM-YYYY");
                           console.log(this.paymentList);
                         });


 [
      {
        "paymentDate": "2018-01-09T09:21:13.759Z",
        "loanAmount": "918553377499",
      },
      {
        "paymentDate": "2017-12-27T09:30:41.276Z",
        "loanAmount": "9880712423",

      },
      {
        "paymentDate": "2017-12-27T07:49:09.892Z",
        "loanAmount": "7259945267",

      }

    ]

I acknowledge that changing my code structure will resolve the issue, however, I am seeking an elegant solution.

this.paymentList.forEach(element => {
var array = [];
var obj = {paymentTime: '', paymentDate: '', loanAmount: ''}
obj.paymentDate= moment(element.paymentDate).format("DD-MMMM-YYYY");
obj.paymentTime = moment(element.paymentDate).format("hh:mm A");
obj.loanAmount = element.loanAmount; 
array.push(obj);
this.paymentList = array;

                         });

Answer №1

Your second method is a good approach with slight modifications.

    let tempPaymentList:any = [];
    this.paymentList.forEach(element => {
      let obj = {paymentTime: '', paymentDate: '', loanAmount: ''}
      obj.paymentDate= moment(element.paymentDate).format("DD-MMMM-YYYY");
      obj.paymentTime = moment(element.paymentDate).format("hh:mm A");
      obj.loanAmount = element.loanAmount;  
      tempPaymentList.push(obj);
    });
     this.paymentList = tempPaymentList;
     console.log(this.paymentList)

It's actually preferable to create a duplicate of the original list and then make modifications to the duplicated list as needed.

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

Creating a global property access expression using the Typescript Compiler API

Currently, I'm grappling with the challenge of creating TypeScript code using the compiler API. Regrettably, official documentation on this subject is scarce, leaving me stranded on a seemingly straightforward task: All I want to do is generate a bas ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

Visibility of an Angular 2 directive

It's frustrating that I can't change the visibility of a reusable directive in Angular2. 1) Let's say I have a login page. I want to control the visibility of my navbar based on whether I am on the login page or logged in. It should be hid ...

Ways to set a button as default clicked in an Array

I have a collection that stores languages and their boolean values. My goal is to automatically set buttons to be clicked (active) for each language with a true value in the collection. Whenever a different language is selected by clicking on its respect ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Issue with Angular 2: The parent class dependency injection is not defined

I have been working on implementing a new service that all other services will extend in order to manage API responses. I came across this insightful discussion Inheritance and dependency injection and here is the parent class code snippet: import {Inje ...

The Vue application is refusing to compile due to a syntax error caused by the presence of 'return' outside of a function

Upon attempting to run a build on my Vue app, I encountered the following syntax error. error in ./src/pages/Calendar.vue?vue&type=script&lang=ts& Syntax Error: 'return' outside of function. (175:4) 173 | getEventColor(event, Even ...

The global CSS styles in Angular are not being applied to other components as expected

Currently utilizing Angular v10, I have a set of CSS styles that are meant to be used across the entire application. To achieve this, I added them to our global styles.css file. However, I'm encountering an issue where the CSS is not being applied to ...

What is the best way to ensure every component in Angular 2 has access to a custom pipe?

I've come up with a unique idea to create a custom rainbowize pipe that wraps each letter in a span with a random color of the rainbow as the css color property. My goal is to implement this custom pipe across all components in my app without having t ...

Angular 12: Ensure completion of all data fetching operations (using forkJoin) prior to proceeding

Within my ngOnInit function, I am looking for a way to ensure that all requests made by fetchLists are completed before moving forward: ngOnInit(): void { this.fetchLists(); this.route.params.subscribe(params => { this.doSomethingWit ...

Ways to fix: Encountering an Unexpected token < in JSON at position 0

Hey there! I've just started dipping my toes into the MEAN stack. I'm currently using Angular to connect to an api.js file, which in turn connects to my mongodb database. However, I've come across this error: ERROR SyntaxError: Unexpected t ...

Can you inherit a type based on the keyof template in TypeScript?

I attempted a small hack to explore how DOM ts files map different element names to their types. My experiment involved trying to have a type MyType extend a different set of fields depending on the value of a string. Here is what I tried: interface Messa ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Ensuring Angular animations run smoothly

When using ngx-toastr with angular/animations for displaying toasts, I noticed a significant delay in the animation when triggering them from a manually created event. export class AppComponent { @ViewChild('iframeElement') iframeElement ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

Pressing a button will reset the Mat Radio Group's Mat Radio Buttons back to their default settings

I have a list of items that need to be rated using radio buttons. I utilized Mat radio group and Mat radio buttons for this purpose. In the scenario below, I need to rate games as good, bad, or none. Once the changes are implemented, I want all the radio b ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this: <div *ngIf="groupCheck; els ...

Creating a customizable filter by using the function of an object

I am currently developing a customizable dynamic filter system, similar to the functionalities offered by Yahoo Screener. To achieve this, I have defined an interface for the available filter fields: export interface FilterField { label: string; se ...

Exploring deep levels of nested FormArrays with Angular 2 and FormBuilder

Currently diving into Angular 2, I am embarking on the challenge of constructing a nested form, validating it, and adding new objects Projects to object GroupProject. Here is a snippet from my TypeScript file: ngOnInit() { this.myForm = this. ...