Unable to append element to array in TypeScript/Angular

Programming Environment: Angular 6


export class Student {
    fullName: string;
    age: number;
    classType: string;
}

export class MyClass {
    public resultData: Array<Student> = [];
    processedData = {
        studentData: [
            {
                name: 'Nayan',
                type: 'toddler',
                classType: 'secondary'
            },
            {
                name: 'Rajesh',
                type: 'infant',
                classType: 'primary'
            },
            {
                name: 'Rithik',
                type: 'toddler',
                classType: 'secondary'
            },
            {
                name: 'Rob',
                type: 'toddler',
                classType: 'primary'
            },
            {
                name: 'Daniel',
                type: 'toddler',
                classType: 'secondary'
            }
        ]
    }
    
    resultData1 =[
        {name:'nayan', age:8, classType:'primary'},
        {name:'Daniel', age:15, classType:'secondary'},
        {name:'Rithik', age:12, classType:'secondary'}
    ]

    someEventClickedFormView() {
        this.processedData.studentData.forEach((data, index) => {
            switch (data.classType) {
                case 'primary': {
                    this.processName(data, 'fullName', index);
                    this.processAge(data,'age',index);
                    break;
                }
                case 'secondary': {
                    this.processName(data, 'fullName', index);
                    this.processAge(data,'age',index);
                    break;
                }
            }

        })
    }

    public processName(data: any, fieldName: string, index: number) {
        this.resultData.push({ fieldName: data.fullName })

        // Error occurs here
    }

    public processAge(data:any,fieldName:string,index:number) {
        this.resultData.push({ fieldName: this.someTransformationToAge(data.age)})
    }
}

A button click event triggers the someEventClickedFormView() function which populates the resultData array with mock data.

An error message is displayed related to the push method in the code snippet above.

Error Message: Argument of type '{ fieldName: any; }' is not assignable to parameter of type 'Student'. Object literal may only specify known properties, and 'fieldName' does not exist in type 'Student'.ts(2345)

The desired format for the resultData array should be as shown below:


resultData =[
    {name:'nayan', age:8, classType:'primary'},
    {name:'Daniel', age:15, classType:'secondary'},
    {name:'Rithik', age:12, classType:'secondary'}
]

Answer №1

In my opinion, the solution lies in applying this straightforward logic. By instantiating an object of the student class and setting its properties based on the logic provided, we can effectively handle the situation. Personally, I fail to distinguish any significant difference between the two cases presented within the switch statement. Therefore, I have opted for a more simplistic approach by directly assigning attributes.

 someEventClickedFormView() {
         
        this.processedData.studentData.forEach((data, index) => {
            Student s = new Student();
            s.name = data.fullName;
            s.classType = data.classType;
            s.age = this.someTransformationToAge(data.age);

            this.resultData.push(s);
            // switch (data.classType) {
            //     case 'primary': {
            //         s.name = data.fullName;
            //         s.classType = data.classType;
            //         s.age = this.someTransformationToAge(data.age);
            //         this.processName(data, 'fullName', index);
            //         this.processAge(data,'age',index);
            //         break;
            //     }
            //     case 'secondary': {
            //         this.processName(data, 'fullName', index);
            //         this.processAge(data,'age',index);
            //         break;
            //     }
            // }

        })
    }

Answer №2

Revise the 3 functions someEventClickedFormView(), processName(), and procesAge() with a single function provided below. Below are 2 options to achieve your desired outcome.

Approach 1 :

someEventClickedFormView() {
    this.processedData.studentData.forEach((data, index) => {
        let studentRecord = {};
        studentRecord['name'] = data.fullName;
        studentRecord['age'] = data.age;
        studentRecord['classType'] = data.classType;
        this.resultData.push(studentRecord);
    })
}

Approach 2: For adding additional dynamic keys to the object besides the existing ones, utilize the solution below where the dynamic field dynamicNameField is assigned with the value passed as a parameter (the example passes fullName as a dynamic key) to the function processDynamicValue() from the code snippet below.

someEventClickedFormView() {
    this.processedData.studentData.forEach((data, index) => {
        let studentRecord = {};
        studentRecord['name'] = data.fullName;
        studentRecord['age'] = this.someTransformationToAge(data.age);
        studentRecord['classType'] = data.classType;
        
        //use the following line and the function processDynamicValue() to append any dynamic name to the key of the studentRecord object before pushing it to the this.resultData array.
        studentRecord=this.processDynamicValue(studentRecord,'dynamicNameField',data.fullName);
        this.resultData.push(studentRecord);
    })
}
processDynamicValue(studentRecord,fieldName,valueToSetToDynamicField){
   studentRecord[fieldName] = valueToSetToDynamicField;
   return studentRecord;
}

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

Testing a component that utilizes an observable time interval in Angular 2

I have implemented a slide-show component with an Input array of slide objects. Each slide is shown based on the time defined in slide.time. Additionally, there are two buttons that when clicked should move to the next item and reset the timer. To achieve ...

Multiple consecutive requests within another (Angular)

Currently, I am deepening my understanding of rxjs and struggling to find an efficient way to manage a sequence of requests. For instance, let's consider the UserService where one of its functions retrieves a user object based on the user id. After ob ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

What is the method to adjust the color of <pagination-controls>?

Seeking assistance with customizing the color of angular pagination from blue to a different hue. Any suggestions? https://i.stack.imgur.com/JjcWk.png I've experimented with various code snippets, but unfortunately, none have yielded the desired res ...

Is it more efficient to have deps.ts per workspace or shared among workspaces?

Currently, I am in the process of setting up my very first monorepo for a Deno-based application. In this monorepo, the workspaces will be referred to as "modules" that the API code can import from, with each module having its own test suite, among other t ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Angular 7 is throwing an error because it is expecting the "path" argument to be a string, but it is receiving an object instead

Whenever I attempt to run tests on my Angular project by typing: ng test --browsers=PhantomJS I discovered that I needed to manually install phantomjs using the following command: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Unit testing the afterClosed() function of Angular Material Dialog with mocking

When I trigger my mat-dialog, I use the following function: accept() { let dialogRef = this.dialog.open(AcceptDialogComponent, { data: { hasAccepted: false } }) dialogRef.afterClosed().subscribe(result => { console.log(result); ...

npm ERROR! Encountered an unexpected symbol < within the JSON data at position 12842

I keep encountering an error every time I attempt to install a package or run npm install. Despite my limited experience with Angular 4, having only started using it a week ago, I am puzzled by this error. Any guidance on how to resolve it would be greatly ...

NG2-Charts are not rendering until the page is manually refreshed

I am currently working on an Angular project utilizing Angular 11. The issue I am encountering pertains to ng2-charts. Essentially, the chart is populated with data from an api-request call to the backend. I have identified where the problem lies, but I ...

Learn the process of integrating app-ads.txt into an Angular localized project hosted on Firebase

I placed the app-ads.txt file in the src folder of my project. In the angular.json file, I included "src/app-ads.txt" in the "assets" section: "assets": [ .... "src/app-ads.txt" ], ... Next, ...

Retrieve the attribute from a TypeScript union data type

Here is the structure that I am working with: export interface VendorState extends PaginationViewModel { vendors: CategoryVendorCommand[] | CategoryVendorCommand; } This is my model: export interface CategoryVendorCommand { id: string; name: str ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

Is there a way to utilize multiple HTML templates with the same TypeScript file?

Is it possible to use different HTML templates for the same TypeScript file, based on an expression in the constructor? I am looking for something like this: <div class="container-fluid"> <app-teste1 *ngIf="teste == '1'> & ...

Indeed / Applying dynamic keys for validation with Formik

Attempting to validate a form with a changing number of fields can be challenging. This scenario involves receiving data from an API that dictates how many input rows are displayed. Each row requires a user input to progress, making validation crucial. Th ...

Experience the power of transforming nested forkjoin operations into observables

Trying to implement a solution in my resolver that involves nested forkjoins and subscribes has been challenging. I attempted using maps, but I still need to fully grasp the concepts of maps/switchMaps/mergeMaps. Even though the code doesn't currently ...

Why is it that the changes I make in the parent component do not reflect in my Angular component?

As I embarked on creating a custom select component, I began with the input below: @Input() options: SelectOption<UserRole>[] = []; The parent component (user editor) utilizes this select component and provides the options as shown below: roleOption ...

Is it possible to determine the type of a class-type instance using class decorators?

Explore this example of faltering: function DecorateClass<T>(instantiate: (...params:any[]) => T){ return (classTarget:T) => { /*...*/ } } @DecorateClass((json:any) => { //This is just an example, the key is to ensure it returns ...

Removing background from a custom button component in the Ionic 2 navbar

Q) Can someone help me troubleshoot the custom component below to make it resemble a plus sign, inheriting styling from the <ion-buttons> directive? In my navbar, I've included a custom component: <notifications-bell></notifications-be ...

Invoking a function on an object of a subclass that derives from an abstract class

In the realm of abstract classes, behold this one: export abstract class BaseStepComponent { /** Behold thy base-step ctor */ constructor() { } abstract getValue(): string; } And lo, here is a component that inherits such abstract glory ...