Trying to add an item to a TypeScript nested array causes an issue: unable to access property 'push' because it is undefined

For a while now, I've been searching on SO trying to find a solution to my issue. It seems that my code isn't as simple as just "push object into array."

In my interface, I have a "Year" property typed with another interface as an array:

   export interface IUser {
        Nickname: string;
        FirstName: string;
        LastName: string;
        Email: string;
        EmergencyContact: string;
        EmergencyNumber: string;
        Year: Array<IYear>;
        IsTeacher: boolean;
        IsAdmin: boolean;
        Uid: string;
    }

    export interface IYear {
        CalendarYear: string;
        PassType: string;
        UserItinerary: IItinerary;
        WaiverStatus: boolean;
        Guests: Array<IGuest>;
        SignupDate: string;
    }

At some point, I need to pass formGroup data into the IYear typed property:

user: IUser = <IUser>{};

createUser(
    firstName: string,
    lastName: string,
    email: string,
    uid: string,
    isTeacher: boolean,
    passType: string) {
    const year: IYear = {
      CalendarYear: this.calendarYear,
      PassType: passType,
      UserItinerary: {} as IItinerary,
      WaiverStatus: false,
      Guests: [],
      SignupDate: this.dateTime
    }
    this.user.FirstName = firstName;
    this.user.LastName = lastName;
    this.user.Email = email;
    this.user.Uid = uid;
    this.user.IsTeacher = isTeacher;
    this.user.IsAdmin = false;
    this.user.Year.push(year);

    return this.user;
  }

The issue arises when I try to push the 'year' property from createUser into the 'this.user.Year' array, resulting in the error

Cannot read property 'push' of undefined

I attempted to pass the values explicitly by key:

this.user.Year['CalendarYear'] = year.CalendarYear;

However, that approach didn't work. Can anyone help identify what mistake I made here?

Answer №1

It is important to remember to initialize the Year array in the user Object to empty before adding any objects to it.

this.user.Year = [];

After that, you can add objects to the array by using the following code:

this.user.Year.push(year);

Answer №2

The error occurs when attempting to push values into an array without first initializing it. To resolve this issue, you must start by initializing an array and then proceed to use the push() method to add values.

  • One option is to create a new IUser instance with year = [{your year}], then continue pushing values to it.
  • Alternatively, you can create a new IUser object with an empty array for year, then push values into it.

Answer №3

Before using your array, make sure to initialize it.

user: IUser = <IUser>{};    
createUser(
    firstName: string,
    lastName: string,
    email: string,
    uid: string,
    isTeacher: boolean,
    passType: string) {
    const year: IYear = {
      CalendarYear: this.calendarYear,
      PassType: passType,
      UserItinerary: {} as IItinerary,
      WaiverStatus: false,
      Guests: [],
      SignupDate: this.dateTime
    }
    this.user.FirstName = firstName;
    this.user.LastName = lastName;
    this.user.Email = email;
    this.user.Uid = uid;
    this.user.IsTeacher = isTeacher;
    this.user.IsAdmin = false;
    this.user.Year=[];
    this.user.Year.push(year);    
    return this.user;
  }

Answer №4

It is essential to check for the existence of the Year property in the user object as well as the presence of the CalendarYear property in the Year object

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

The error message "NodeJS TypeError: Model is not a constructor" indicates that

I am facing an issue with my Angular5 app making requests to my NodeJS Api. Specifically, when I try to make a put request, it works the first time but throws an error on the second attempt saying that my Model is not a constructor. In my NodeJS backend, I ...

Error in Swift: Trying to access an index that is outside the bounds of a two-dimensional array

I am facing an issue with a 2 dimensional array of String in my code. I initialize the array with a default value String, but when I try to access an element from it, I encounter out of range errors. class MyClass: UIViewController { var bodies = [[Strin ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

How can we enhance the angular material date picker by inserting a div on either the left or right side to display

I'm looking to customize the style of an angular material datepicker and include a box that displays the selected date, similar to the image shown here: enter image description here Does anyone have suggestions on how to achieve this? Any assistance ...

Exploring the usage of array map parameters in rxjs 6 when combined with withLatestFrom

Prior to Rxjs 6, we were able to achieve the following: interface TypeA { payload: any; } source$.pipe( withLatestFrom(source2$, (source1: TypeA, source2: TypeB) => ({ payload: source1.payload, source2 }) ), ) In the resultSelector method ...

Detecting if a click listener is registered within an Angular 2+ component

In the process of developing a reusable component featuring a rounded image thumbnail, I am aiming to incorporate functionality that detects if a click listener has been assigned to it. If a developer has applied a (click)=anyClickCallbackFunction() on the ...

Calculating numbers with Math.ceil will result in an increase of 1

After using Math.ceil, one value was rounded up to 50 and the other to 80. However, when I added these two values together, the result unexpectedly turned out to be 131. console.log(Math.ceil(e.currentTarget.clientHeight) // 50 console.log(Math.ceil(e.cu ...

Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe. Here is an example of how one of these objects is structured: ...

How can a function in systemVerilog be defined to return a vector or array of undetermined size?

Is it possible to create a function that returns a vector or array with an unspecified size? The return values can vary, such as bit [15:0], bit [10:0], bit [2:0]... I desire the capability to define something similar to this: function bit [] foo (in ...

The outcome of Contains function is coming back as negative

Recently, I was working on a project that I cloned from GIT, which involved a bot. However, I encountered an issue where the 'contains' function used by the bot was not functioning properly. After conducting some research using Google, I discove ...

Angular making sequential api calls

I have the following code where I am making one API call after another, with the second API call nested inside a subscribe. Is it possible to use mergeMap in this scenario to avoid multiple subscribe calls? Here is my current code: saveEmployees(empObje ...

Unable to attach to 'leafletOptions' as it is unrecognized as a property of 'div'

It seems like I keep encountering this problem, which is often resolved by adjusting import statements. Right now, my imports look like this: import { LeafletModule } from 'node_modules/@asymmetrik/ngx-leaflet'; import * as L from 'leaflet& ...

Retrieving user input from one component to be used in another component in Angular

I'm currently working on a structure that involves a navbar component and a form component https://i.stack.imgur.com/nPRLO.png Initially, I have a navbar component where I load user data using an ID stored in the session. In the right side component ...

Is it possible to invoke a method using a jQuery id selector within an Angular 2 template?

Is it possible to pass an id selector to a method from a template? <ul> <div id="temp">some text</div> <button (click)="methodName1(is it possible somehow? --> $('#temp'))">Label</button> </ul> ...

Ways to display the SearchFilter textbox in an Angular Multiselect Dropdown, even when there are no items loaded

Angular version: 8 ng-multiselect-dropdown version: ^0.2.10 I am facing a situation where the user needs to start typing in the search field to load results dynamically into the dropdown. However, in the ng-multiselect-dropdown component, the search box ...

How come validation errors are not appearing on the view?

As I continue to practice, I am working on this form. It successfully displays a console message, indicating the wiring is correct. However, an issue arises when I submit the form without entering any text in the input field, as it fails to show a validati ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

The function cb() was never invoked, resulting in an error during the npm install process

I'm having trouble installing node modules in my angular project. Running npm install gives me this error: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.community> ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Sending Information to Routes - Error: No Routes Found to Match

I recently tried implementing a solution from an article () to pass an ID between modules in order to use it as a search filter. However, I encountered the "cannot match any routes" error and have been struggling for some time since I'm new to Angular ...