Attempting to add a new property to every object in an array using TypeScript

In my Angular project, I have a specific code block that retrieves an array of objects containing contact records.

Within a 'forEach' loop, I am generating a new field for each contact record to store the user's initials.

The goal is to add this newly created 'userInitials' field to the appropriate record in the array.

I attempted the following code snippet, however, it seems to be adding new objects instead of new fields. Removing the object brackets results in errors.

    let initialHold: any;
    let contactWithInitials = [];

    this.contacts.forEach( eachObj => {
      if(eachObj.first_name){
        initialHold = eachObj.first_name.charAt(0);
      }
      if(eachObj.last_name){
        initialHold += eachObj.last_name.charAt(0);
      }

      this.contacts.push({'userInitials':initialHold});

    })

Answer №1

Replace

this.contacts.push({'userInitials':initialHold});
with
eachObj['userInitials'] = initialHold
. If you aim to modify the original object, ensure to assign the new property directly to eachObj after creating it.

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

Tips for incorporating live stock price updates into an Ionic application

Using a 3rd party API, I have successfully displayed a list of stock prices on cards. However, I am struggling to update the real-time data on each card with each second changes. I have attempted various methods, but the entire API is being fetched inste ...

Angular 2: Toggle multiple checkboxes with a single click

I am faced with a scenario where I have 5 checkboxes implemented as shown below <input type="checkbox" [checked]="chk1" (change)="chk1 = !chk1" />chk1 &nbsp; <input type="checkbox" [checked]="chk2" (change)="chk2 = !chk2" />chk2 &nbsp; ...

Resolving the Challenge of Disabling typescript-eslint/typedef in Angular 13 with ESlint

I started a fresh project in Angular 13 and configured typescript-eslint by running the command below: ng add @angular-eslint/schematic I made changes to my .eslintrc.json file where I disabled the rules for "typescript-eslint/typedef" and "typescript-esl ...

Applying CSS styles to a shadow DOM element will not produce the desired visual

I'm encountering an issue while attempting to apply CSS to an element within a shadow-root by adding a class to it. In my Angular component, I have the following code: CSS .test { border: 1px solid red; } TS document.getElementById('my-div&a ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

Validator for ngModel in Angular 2 conveniently located within the component

Trying to simplify the process of implementing a custom validator logic for ngModel, I have a pre-defined model (interface) that already stores all necessary data. Why go through the trouble of creating an identical schema with FormControls when the requir ...

Strategies for retaining a list of chosen localStorage values in Angular6 even after a page refresh

When I choose an option from a list of localStorage data and then refresh the page, the selected data disappears. selectedColumns: any[] = []; this.listData = [ { field: "id", header: "Id", type: "number", value: "id", width: "100px" }, { field: "desc ...

Type-constrained generic key access for enhanced security

While attempting to create a versatile function that retrieves the value of a boolean property using a type-safe approach, I encountered an issue with the compiler not recognizing the type of my value. type KeyOfType<T, V> = keyof { [P in keyof T a ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

Challenges Experienced by AoT in Live Operations

So in my project, I have various components and services included where necessary. To ensure their accessibility, I made sure to declare all the services as private within the constructor. Here's an example: constructor(private myService: MyService) ...

The Angular Project I downloaded from Github is working fine on my Windows PC, but when I tried to run it on my Mac,

I am encountering an issue with my angular/dotnet project. I initially started working on it on my Windows PC using Visual Studio Code, but now that I need to work on it on my laptop, I tried downloading it from Github. However, after cloning the project a ...

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...

Update the nest-cli.json configuration to ensure that non-TypeScript files are included in the dist directory

I've been searching for a solution for hours now: I'm developing an email service using nestJS and nest mailer. Everything was working fine until I tried to include a template in my emails. These templates are hbs files located in src/mail/templ ...

Leverage the component's recursive capabilities to build a tree structure from within

Is it feasible to use a component within itself? If so, where can I find more information on this? I am facing the following scenario: I have a list of main items, each main item has a subitem (which looks like the main item), and each subitem can have i ...

What is the best way to configure eslint or implement tslint and prettier for typescript?

In my React/Redux project, I recently started integrating TypeScript into my workflow. The eslint configuration for the project is set up to extend the airbnb eslint configurations. Here's a snippet of my current eslint setup: module.exports = { // ...

ngx: navigate to the specified URL once the user has been successfully logged in

I am faced with a dilemma where I must wait for my authentication server to return my token before calling my APIs. I am looking for a solution to ensure that my authState.token is not null before dispatching LoadMyStuffFromApi. I have implemented two res ...

What is the process for creating a method within a class?

Here is the current structure of my class: export class Patient { constructor(public id: number, public name: string, public location: string, public bedId: number, public severity: string, public trajectory: number, public vitalSigns: ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

In Angular, the data retrieved from the API will only appear on the page once it has been manually

Recently, I started working on an Angular project and encountered a problem with data display after each component routing. Initially, the data is not displayed until the page is reloaded. You can see the issue in the screenshots: https://i.sstatic.net/5My ...