In this tutorial, we will explore the process of extracting nested array values from JSON data and displaying it within a listview template using

  • In the JSON structure below, if you look at the marks array, I need to extract and display the body value of the marks array: first, second, and third.

  • The values first, second, and third are located inside the marks Array. I am unsure how to retrieve these values and display them in a listview template.

  • I simply want to display all three values in each listview item position.

students.json:

[
    {
        "id": 1,
        "name": "denver",
        "marks": [
            {
                "identity": [],
                "body": {
                    "first": "Pollard",
                    "second": "Bravo",
                    "third": "Kevin"
                } 
            },
            {
                "identity": [],
                "body": {
                    "first": "Michael",
                    "second": "Waugh",
                    "third": "Stone"
                }
            }
        ]
    },
    {
        "id": 2,
        "name": "kallis",
        "marks": [
            {
                "identity": [],
                "body": {
                    "first": "Yuvi",
                    "second": "Maxwell",
                    "third": "Rock"
                }
            },
            {
                "identity": [],
                "body": {
                    "first": "Steve",
                    "second": "Laughlin",
                    "third": "Jeff"
                }
            }
        ]
    },

    {
        "id": 3,
        "name": "younis",
        "marks": [
            {
                "identity": [],
                "body": {
                    "first": "Ben",
                    "second": "Stokes",
                    "third": "Smith"
                }
            },
            {
                "identity": [],
                "body": {
                    "first": "Archer",
                    "second": "Matt",
                    "third": "Glenn"
                }
            }
        ]
    }

]

app.component.html:

<StackLayout height="100%">

    <ListView [items]="studentList" class="list-group" height="70%">
        <ng-template let-item="item" let-i="index">
            <StackLayout class="input-border">

                <Label [text]="item.name" class="module-title"></Label>

             <!--   <StackLayout>
                    <Label [text]="item.first" class="user-title"></Label>
                    <Label [text]="item.second" class="item-title" textWrap="true"></Label>
                    <Label [text]="item.third" class="item-title" textWrap="true"></Label>

                </StackLayout>  -->

            </StackLayout>
        </ng-template>

    </ListView>

App.component.ts:

import { Component, OnInit } from "@angular/core";
import { ObservableArray } from 'data/observable-array'
import { Student } from './model/Student';
import * as Application from "application";
import { AppService } from './app.service'

@Component({
    selector: "app",
    moduleId: module.id,
    providers: [AppService],
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})

export class AppComponent implements OnInit {
    private studentList: ObservableArray<Student>;

    constructor(private appService: AppService) {
    }
    ngOnInit() {
        this.studentList = this.appService.getStudent();
    }

}

app.service.ts:

import { Injectable } from '@angular/core'
import { Student } from './model/Student'
import { ObservableArray } from 'data/observable-array'

var getData = require("./model/student.json");

@Injectable()
export class AppService {

    getStudent(): ObservableArray<Student> {
        var studentList: ObservableArray<Student> = new ObservableArray<Student>();

        console.log("StudentArray", JSON.stringify(getData));

        for (var i = 0; i <getData.length; i++) {
            var student = new Student();
            student.name = getData[i].name;
            console.log("nameStudent", getData[i].name);


        studentList.push(student);

        }

        return studentList;

    }
}

Answer №1

Given that marks is an array consisting of Objects, you can retrieve these values using array access followed by field access:

<StackLayout>
    <Label [text]="item.marks[0].body.first" class="user-title"></Label>
    <Label [text]="item.marks[0].body.second" class="item-title" textWrap="true"></Label>
    <Label [text]="item.marks[0].body.third" class="item-title" textWrap="true"></Label>
</StackLayout>

However, if you wish to display all marks without manually specifying an index for marks, another loop will be required.

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

Dealing with NPM problems during Angular 9.0.7 setup issues

I encountered a problem after a recent Windows update that corrupted my system. I had to reinstall Windows, and now I am unable to run my Angular project, which was originally in version 9.0.7 with a package.json file. I tried installing Angular 9.0.7 glob ...

What is the process for deleting all views in Ionic 2 apart from the login view?

I created an Ionic 2 app with tabs using the following command: ionic starts project1 tabs --v2 Next, I added a new page and provider to the project: ionic g provider authService ionic g page loginPage After a successful login, I set the root to the Ta ...

Tips for creating an input box that only accepts floating point numbers:

I have a custom component - a text box that I am using in two different places. In one location, it accepts integers and in another, floats. For the integer validation (where dataType=2), I have successfully implemented it. However, for the float validat ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Create an object with identical keys as another object

I need to create a mapping between two objects. The first object can have keys of any string type and values of a generic type. I want to map the second object with the same keys, allowing different types for the values (ideally extracted from the generi ...

Is it possible to design a Typescript type that only contains one property from a defined set and is indexable by that set as well?

I have the different types listed below: type OrBranch = { or: Branch[] } type AndBranch = { and: Branch[] } I need a type called Branch that can either be an OrBranch or an AndBranch. I initially attempted this: type Branch = AndBrand | OrBranch ...

Having trouble with Angular Ng2-file-Upload's Upload.all() method not successfully sending files to the API

Dealing with the challenge of uploading files in mp4 and jpg formats, I have set up 2 separate instances of FileUploader with custom validation. Upon clicking the upload button, I attempt to merge the files from both instances into a single FileUploader ...

What is the best way to utilize the typescript module for detecting and managing typescript errors and warnings in your code?

Currently, I am experimenting with the typescript module to programmatically detect typescript errors. Below is a simplified version of what I have been working on: var ts=require('typescript') var file_content=` interface Message{ a:string ...

Tips for packaging NPM packages from the local directory

Hey there! I recently downloaded an npm module from GitHub and made some changes to it. Now, I am trying to install it locally using `npm install`, but the files are not being compiled and I am still seeing .ts instead of .js files. I have tried following ...

Error: React Component not rendering correctly - Element Type Invalid

React Uncaught Error: Element type is invalid Encountering a problem in my React application where the following error message appears: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite compone ...

Configuring NextJs routes with multiple parameters

Seeking guidance on structuring files in Nextjs for handling multiple URL parameters. Can anyone offer advice? The given URL structure is: /api/upload?file=${filename}&fileType=${fileType} This is the current file structure: app api upload ...

Issue with Angular Testing: unable to resolve all parameters for Store: (?, ?, ?)

I am currently encountering an issue while trying to declare my ngrx/Store within the spec file for testing a container component. To tackle this problem, I began by importing the store and implementing the following code snippet inside the beforeEach bloc ...

File resolution issue with TypeScript

While I am aware that using TypeScript outFile is generally advised against, I currently have no choice but to utilize it until a more suitable solution like AMD can be implemented. It seems like there may be a "module splitting issue" in my project. In t ...

Getting the version from package.json in Next.js can be easily achieved by accessing the `version

In my quest to retrieve the "version" from the package.json in a Next.js application, I encountered a roadblock. I attempted using process.env.npm_package_version, similar to how it is done in a Node application, but unfortunately, it returned undefined. ...

Migrating from AngularJS to the latest version, Angular12, may present some challenges such as the error message: "Unable to resolve

Currently, I am in the process of migrating from AngularJS 1.8.2 to angular 12. After transitioning from grunt to webpack for compilation, my next step is tackling the actual migration to Angular. My initial goal is to have Angular and AngularJS coexist si ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

Access navigation through Google Maps on an Android device directly from the website

Currently, I am in the process of developing an angular 4 website that fetches a list of latitude and longitude coordinates from the server. One of the key features on this website is a button that takes the user to Google Maps, where a route is constructe ...

Unable to process JSON request in Node.js

I have the following data in Angular that I need to pass to a Node API. The data includes a JSON object that is being sent to the Node API using the POST method. var myData = { "que": { "id": 1, "status": 1, "option": [ ...