loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I'm having trouble reading it.

data = [{
"Items" : [ {
  "Key" : "9009",
  "type" : "fsdf",
  "name" : "sdfsdfn",
  "spec" : "dsfsdfdsf",
  "Attributes" : {
    "category" : "Mobile",
    "orderDate" : "2019-03-07 14:40:49.2",
    "startDate" : "2019-03-07 14:40:49.2",
    "status" : "CREATED"
  },
  "characteristics" : [ ],
  "relatedItems" : {
    "contains" : [ "1", "2", "3"]
  },
  "sellable" : false
}, .... {} ]

Answer №1

To retrieve all properties of an object, you can utilize the Object.keys method. When incorporating it into an angular template, it's necessary to create a wrapper method in your component.

For a visual example, I've quickly put together a demo showcasing nested tables using a template. Check it out Here.

The concept is demonstrated below:

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <ng-template #table let-obj="obj">
      <table style="border: 1px solid black">
        <thead>
          <tr>
            <td *ngFor="let key of getKeys(obj)">
              {{key}}
            </td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td *ngFor="let value of getValues(obj)">
              <div *ngIf="isValue(value)">
                  {{value}}
              </div>
              <div *ngIf="!isValue(value)">
                <ng-container *ngTemplateOutlet="table;context:ctx(value)"></ng-container>        
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </ng-template>

    <div *ngFor="let d of data">
      <ng-container *ngTemplateOutlet="table;context:ctx(d)"></ng-container>
    </div>

  `,
})
export class App {
  data:any[];
  constructor() {
    this.data =  [ {
      "Key" : "9009",
      "type" : "fsdf",
      "name" : "sdfsdfn",
      "spec" : "dsfsdfdsf",
      "Attributes" : {
        "category" : "Mobile",
        "orderDate" : "2019-03-07 14:40:49.2",
        "startDate" : "2019-03-07 14:40:49.2",
        "status" : "CREATED"
      },
      "characteristics" : [ ],
      "relatedItems" : {
        "contains" : [ "1", "2", "3"]
      },
      "sellable" : false
    }];
  }
  ctx(obj) {
    return { obj };
  }
  getKeys(obj) {
    return Object.keys(obj);
  }
  getValues(obj) {
    return Object.values(obj);
  }
  isValue(obj) {
    return (obj !== Object(obj));
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

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

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

Multiple keyup events being triggered repeatedly

Currently, I am developing an Angular 4 application. Within my component's HTML, there is a textbox where users can input text. As soon as the user starts typing, I want to trigger an API call to retrieve some data. The current issue I am facing is t ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

The power of Typescript shines in its ability to ensure type safety when working with conditional

I am struggling with typing a simple function in Typescript that takes a union type and a boolean as parameters. Here is the code snippet: type A = 'a' | 'A'; function f(a: A, b: boolean): string { if (b) { switch (a) { ...

Client-side database integrated in web application

As I work on a project for healthcare providers, the handling of sensitive data is crucial. Since I am utilizing server-side operations solely for CRUD tasks, I have considered whether it would be viable to deliver the Angular application directly to the u ...

Having trouble with the onChange function within the rc-field-form wrapper

I created a wrapper for the Field component from the rc-field-form package as shown below: import * as React from "react"; import Form from "rc-field-form"; import type { FieldProps } from "rc-field-form/lib/Field"; const { F ...

The subscription data for nested classes appears to be displaying as undefined

In my current project, I am utilizing Angular 8 and facing an issue with a nested class. The problem arises when trying to access data from an observable subscribe operation in the child class (Players) within the main Tournament class. Until the data is r ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

Changing the host domain to a non-.com extension in Angular-cli while serving for development

While running an ng serve on my angular cli build, I am attempting to use a .ca domain as the host in order to address CORS and cookie issues during development. Interestingly, when using a .com domain, everything functions smoothly: Functioning with .com ...

The email input should be the same red color as the other inputs, but unfortunately it is

When I enter the email address with first name and last name, it shows as invalid. However, the color on the CSS does not match. I am confused about why there is a difference between the two. I tried changing the type of email to text, but still no luck. ...

Error in TypeScript: Angular Jasmine - The argument given as type 'string' cannot be assigned to a parameter expecting type 'never'

Currently, I am in the process of writing test cases for Angular using Jasmine 3.6.0 and TypeScript 4.1.5 with "strict": false set in my tsconfig.json file. One particular task involves spying on a component method called 'close', and following ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Retrieve information from two distinct observables from within the resolver function

I'm facing an issue with my services that work on the observable principle. I am trying to fetch the results of 2 services inside a resolver to display on my page. However, the data being displayed on the page is just an empty data object. I even trie ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

Creating a method to emphasize specific words within a sentence using a custom list of terms

Looking for a way to highlight specific words in a sentence using TypeScript? We've got you covered! For example: sentence : "song nam person" words : ["song", "nam", "p"] We can achieve this by creating a custom pipe in typescript: song name p ...

Typescript error: Undefined reference to 'DhImportKeyParams'

Working on a project, I encountered an issue with a third-party library written in Typescript 3.7. The outdated library depended on the 'lib' that contained an interface called DhImportKeyParams. However, my current project uses Typescript 4.6 wh ...

Retrieving source in Angular from an async function output within a specified time limit

I have a quick query :). I'm attempting to retrieve the image src from an async function, but so far, I haven't had much success. This is what I have: <img [src]="getProductImage(articleNumber)"/> and in my TypeScript file: publi ...

What are the steps to implement SignalR Stream in an ASP.NET Core Angular application?

Attempting to utilize SignalR stream for sending real-time data to clients and displaying it on an Angular component's template. Below is a snippet of my code, where this function is linked to a button (click) event in the template: getMessage(m ...

ng2-map - Double click to trigger two separate events

Currently, I am utilizing ng2-map to showcase a Google map in Angular 2. I have implemented the click event to capture any clicks made on the map. However, it seems that each click is generating two events rather than just one: 1) _.nk {latLng: _.F, pixel ...

Should I implement jquery within angular 2, or opt for the current css/js frameworks available?

Embarking on the development of a website with Angular 2, my deadline is set within a month. I need to select a CSS/JS framework that seamlessly integrates with Angular 2. While using jQuery within Angular 2 is discouraged, I am curious if there are altern ...