Problem with manipulating objects and arrays in typescript while iterating through a JSON object

I have a JSON object named allDepartments, which consists of an array of custom data type contactItem:

export interface contactItem {
        id: number;
        position: string;
        name: string;
        email: string;
        extension: number;
        phone: Text;
        department: string;
    }

    public allDepartments: contactItem[]; //interface defined in contactService
    

This is how allDepartments looks like:

[
        {
            "id": "1",
            "position": "Director of Pathology and Laboratory Medicine",
            "name": "Dr. Niall Swan",
            "email": "[email protected]",
            "extension": "4798",
            "phone": "012214798",
            "department": "General"
        },
        {
            "id": "2",
            "position": "Laboratory Manager",
            "name": "Donal Murphy",
            "email": "[email protected]",
            "extension": "4510",
            "phone": "012124510",
            "department": "General"
        },
        {
            "id": "4",
            "position": "Laboratory Manager",
            "name": "Donal Murphy",
            "email": "[email protected]",
            "extension": "4510",
            "phone": "012124510",
            "department": "General"
        },....
    

If the department key in a contactItem is set to biochemistry, I want to add that contactItem object to an array called biochemistry:

public biochemistry: contactItem[];

    // Iterate through the array and assign biochemistry contacts 
    console.log("contacts.page.ts: trying to get biochemistry data...");

    for (var contact in this.allDepartments){
        console.log("contact = " + this.allDepartments[contact].department);
        if (this.allDepartments[contact].department == "biochemistry"){
            this.biochemistry.push(this.allDepartments[contact]);
            console.log("biochem object: " + this.allDepartments[contact]); // Array of objects
        }
    }
    

An exception is occurring:

TypeError: undefined is not an object (evaluating 'this.biochemistry.push')

The syntax for pushing an object to a TypeScript array seems correct, so I am unsure about the issue. Any insights would be appreciated.

Answer №1

To start using the array, I needed to initialize it first:

let biochemistryItems: contactItems[] = [];

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

What is the recommended data type for the component prop of a Vuelidate field?

I'm currently working on a view that requires validation for certain fields. My main challenge is figuring out how to pass a prop to an InputValidationWrapper Component using something like v$.[keyField], but I'm unsure about the type to set for ...

npm: dealing with white spaces in package.json scripts

Having trouble getting this to work in a package.json file "zip": "C:\\Program Files\\7-Zip\\7z.exe a -tzip -mx9 yes.zip folder\\*" Encountering an error: 'C:\Program\' is not recognized as an ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

Declaring a Static Method in TypeScript within a React Functional Component

I am attempting to access static methods from my functional component in React. Below is a brief example of what I am trying to achieve (it works in regular JavaScript). The issue arises on line 10 with the code const x = ... TS2339: Property 'GetM ...

Having trouble with React npm start: 'No chokidar version found' error occurring

After cloning my React-Typescript app on Github Pages and attempting to make some changes, I encountered an issue. Despite running npm install to install all dependencies, when I tried to run npm start, I received the following error message: https://i.st ...

Tips for creating an HTTP only cookie in NestJS

Currently, I am in the process of incorporating JWT authorization with both an accessToken and refreshToken. The requirement is to store these tokens in HTTP-only cookies. Despite attempting this code snippet, I have encountered an issue where the cookies ...

Click on the marker to view information about the location stored in the HashMap

A function is being used to store the json data in a hashmap. private Map<MarkerOptions, JSONObject> markersMap = new HashMap<MarkerOptions, JSONObject>(); private void parseLocationResult(final JSONObject result) { String id, place_ ...

Prohibit using any as an argument in a function if a generic type is

I have attempted to implement this particular solution to prevent the calling of a generic function with the second type being equal to any. The following code snippet works fine as long as the first generic parameter is explicitly specified: declare fu ...

All authentication logic in Angular encapsulated within the service

I am considering moving all the business logic into the auth service and simply calling the method on the component side. Since none of my functions return anything, I wonder if it's okay or if they will hang. COMPONENT credentials: Credentials = ...

Utilizing structs to replace arrays and implementing a loop in C++

My current working code calculates interest based on certain conditions. #include <iostream> using namespace std; const int MAXACCOUNTS = 8; int interest(double Balance[], int AccountNumber[], int DaysSinceDebited[], int MAXACCOUNTS); int main() { ...

"Facing difficulties in personalizing the PrimeNG Quill Editor within an Angular environment

In my Angular 7 project, I am utilizing the PrimeNG Editor (based on Quill) and I have a need to customize the toolbar. Despite experimenting with various configuration options in both HTML and JavaScript, the only modification I have been able to make is ...

Analyzing the efficiency of the Scala Arrays tail function

According to Scala documentation, the performance of accessing the tail for an Array sequence is stated as Linear, while accessing the head is described as having a performance of Constant. Despite the entire block containing array elements being brought ...

What is the best way to extract all "conditions" nested under the key "logic" at the 0th index in a JSON object?

I need to manipulate a nested object by removing every "condition" where the key is "logic" and the value is 0 from it. Here is an example of the object structure: Original input: [ { "conditions": [ { "logic": "AND", "paramet ...

What kind of parameter should be used that implements IEnumerable and has a Count property?

Often times, it can be beneficial to optimize methods that accept an array to instead accept more versatile classes that implement IEnumerable and have a Count or Length property. For example: public static T GetNextItem<T>(this Random random, T[] ...

Is it possible to assign a type to an anonymous object in TypeScript?

Check out the code snippet below: hello({ name: "Michael" } as x) // <-- Except missing id here, but it doesn't type x = { id: string name: string } function hello(x: any) { console.log(x) } TS Playground No error is thrown de ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

determining the array size in C99

Here is a basic C program: #include <stdio.h> #include <stdlib.h> void process(int array[static 5]){ int i; for(i=0; i<5; i++) printf("%d ", array[i]); printf("\n"); } int main(){ process((int[]){1,2,3}); ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Having trouble with UI-Grid not showing your JSON data?

I have successfully implemented the accessor syntax for binding my UI-Grid control. However, despite not encountering any errors or issues with data retrieval, I am receiving a warning regarding Mutating the prototype. The structure of my JSON data is as ...