Having trouble with iterating through nested array objects in Angular 4 component

I am facing an issue when attempting to iterate over a nested array object using the code below. It seems to be throwing an error saying "undefined". Could this be related to Typescript or angular4?

import { Process, Event } from "./process";

export class ProcessComponent {

 process: Process;

someMethod() {

    for(let val of this.process.events) {
        console.log(val.notes); // The console is displaying undefined.
 }
}

process.ts

export class Process {
    id: number;
    includeSaturdays: boolean;
    includeSundays: boolean;
    events: Event[];    
}

export class Event {
    id: number;
    date: number;   
    notes: string;
}

Sample data :

{
    "id": 1572734,
    "includeSaturdays": false,
    "includeSundays": false,
    "events": {
        "event": [
            {
                "id": 1587532,
                "date": 1483209000000,                
                "notes": "New year"
            },
            {
                "id": 1587533,
                "date": 1495909800000,
                "notes": "Memorial day"
            }]
 }
}

Answer №1

Considering the data structure you provided, a more suitable approach would be to implement the following solution.

newFunction() {

 this.process.events.event.map(item => console.log(item.notes))

}

Since you are dealing with an array of objects rather than a single large one, using map() appears to be the better choice for this scenario.

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

Storing the subscription value retrieved from an API in a global variable

I am trying to find a way to make the data retrieved from an API accessible as a global variable in Typescript. I know that using subscribe() prevents this, so I'm looking for a workaround. Here is the API code: getResultCount(category:any):Obs ...

Setting a default time on a p-calendar: A step-by-step guide

I am currently using the following p-calendar component in my webpage: <p-calendar [style]="{'width':'100%'}" [inputStyle]="{'width':'100%'}" dateFormat="dd-mm-yy" [fo ...

In a carousel slider, the height and width of divs are not set to specific dimensions

For a code snippet, you can visit this link: here The html: <html lang="en"> <head> <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet"> <link href="https://ma ...

Tips for Sending Specific Row Information to Server in Ionic 3

Successfully pulled contacts from the device into my list page, but struggling to send specific contact details (name and number) to the server. Can anyone provide guidance on accomplishing this in Ionic? ...

Accessing an item within a JSON object using jQuery

Trying to access an element within a JSON object, part of the code is shown below: { " academy": { "business": { "E-commerce": [ I have successfully accessed the academy as the first element using the following code: $.getJSON("p ...

What methods are available to load sections of a complex SVG shape asynchronously?

I'm currently in the process of creating a website with a geographic map built using SVG, pulling data from OpenStreetMap. Due to its large size and potential for transformations such as zooming and moving, only a portion of it will be visible on the ...

Encounter Unspecified Variable Within app.get(...)

Express Enigma After setting the variables const username = "a" const password = "a" I attempted to reassign them using {username, password} = req.body (This was within a form on /createaccount) However, I encountered an er ...

Tips for stopping the textarea from moving around as you type and avoid it hitting the bottom of the page: Utilize JQuery and

As I type into the auto-sizing textarea, the text runs to the bottom of the page and causes it to dance uncontrollably with each key press. This forces me to constantly scroll down to see what's happening. How can I prevent this page dancing and keep ...

AngularJS Compile directive allows you to specify functions that you want to run in

Can someone assist me in understanding how to call an external function from a built-in compile directive? Here is a code example: http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview This is the HTML: <!DOCTYPE html> <html ng-app="app"> ...

Using async/await with Axios to send data in Vue.js results in different data being sent compared to using Postman

I am encountering an issue while trying to create data using Vue.js. The backend seems unable to read the data properly and just sends "undefined" to the database. However, when I try to create data using Postman, the backend is able to read the data witho ...

What steps should I take to show the content on different menu selections?

Check out my full code snippet. <html> <head> <meta charset="utf-8"> <title>Title</title> <link rel="stylesheet" href="https://code.jquery.com/mobile/1.5.0-rc1/jquery.mobile ...

Ways to activate a function upon validation of an email input type

Within my HTML form, there is an input type="email" field that requires a valid email pattern for acceptance. I am attempting to send an AJAX request to the server to confirm whether the entered email already exists in the database after it has been verif ...

Troubleshooting issue: Angular dropdowns not functioning properly with Bootstrap framework

Despite importing Bootstrap 4 and other necessary libraries like jquery and popper into my Angular app using npm, I am facing an issue where the dropdown in the top navigation bar does not work. I am hesitant to bring in additional Angular Bootstrap librar ...

What could be causing the CORS policy to block GET requests?

In my recent project, I have been developing a hybrid app that utilizes express and cors. This application is responsible for sending both get and post requests from a client JavaScript file to a server file. Everything was functioning smoothly until I sta ...

The process of uploading a file is interrupted by an AJAX Timeout

My HTML form includes a file input field that utilizes AJAX to upload the selected file, complete with a progress bar. However, I encountered an issue where the request would hang without any response. To prevent this from happening in the future, I aim t ...

Tips for passing the same value to two components using vuejs $emit

Can someone help with typing in Main, where the value can also be Test World? You can view a sample here >>> Sample The issue I'm facing is that when a user adds an item to the cart, the cart shows one more than it should. I've tried t ...

React: A Guide to Selectively Targeting the State of List Items

Exploring React, I am currently working on creating a dynamic navigation menu by utilizing the map() function to target the ul and li components efficiently while avoiding code duplication. However, I am encountering an issue where clicking to open one com ...

Tips for accentuating a chosen cell

When selecting an item from the list, I want to highlight the selected item. How can I achieve this? Here is the code snippet: <li class="nav-item dropdown"> <div class="dropdown"> <a class="nav-link dropdown-toggle text-white" hre ...

ngOnInit unable to properly listen to event stream

I've been trying to solve a persistent issue without success. The problem involves the interaction between three key elements: the HeaderComponent, TabChangingService, and TabsComponent. Within the HeaderComponent, there are three buttons, each with a ...

Next.js version 10 Internationalization - default locale always returned by getStaticProps

I'm in the process of setting up a new project with the latest version of Next.js and implementing internalisation using domain routing as described here. My configuration within the next.config.js file looks like this: i18n: { locales: [' ...