Accepting a JSON array as a JSON object is a feature of Angular 2+

Hey there. I'm currently dealing with a JSON object that showcases arrays as JSON objects inside. This is making it difficult for me to iterate over them. Any suggestions or tips on how to handle this would be greatly appreciated! The image below illustrates the types shown in VS Code. Even though I have initialized placeTypes as an empty array, it appears as an empty object.

InitialModel = [
    {nearByTypeName : "ex 1",id: 1,placeTypes:[
      {placeTypeId:1,placeTypeName:"ex1.1",
      places:[]}
    ]},
    {nearByTypeName : "ex 2",id: 2,placeTypes:[
      {id:2,placeTypeName:"ex 2.1",places:[]},
      {id:3,placeTypeName:"ex2.1.1",places:[]}
    ]}
  ]

https://i.sstatic.net/806Xy.jpg

https://i.sstatic.net/8LL7F.png

Answer №1

Here is a suggested approach:

const startingData = [
      {
        category: "example 1", id: 1, types: [
          {
            typeId: 1, typeName: "type 1.1",
            items: []
          }
        ]
      },
      {
        category: "example 2", id: 2, types: [
          { typeId: 2, typeName: "type 2.1", items: [] },
          { typeId: 3, typeName: "type 2.1.1", items: [] }
        ]
      }
    ];


    for (const data of startingData) {
      for (const type of data.types) {
        // carry out operations
      }
    }

Note: If you encounter an issue with using foreach loops due to an error message like "Error: Cannot invoke an expression whose type lacks a call signature," it may be because of differences in property names. To resolve this, make sure that the property names match in all elements of your array. For example, renaming id in the 2nd element to typeId should solve this problem.

 const startingData = [
  {
    category: "example 1", id: 1, types: [
      { typeId: 1, typeName: "type 1.1", items: [] }
    ]
  },
  {
    category: "example 2", id: 2, types: [
      { typeId: 2, typeName: "type 2.1", items: [] },
      { typeId: 3, typeName: "type 2.1.1", items: [] }
    ]
  }
];


startingData.forEach(element => {
  const temp = element.types;
  temp.forEach(val => {
    // perform operations
  })
});

Answer №2

Here's an example of looping through nested loops:

component


  InitialModel = [
    {nearByTypeName : "ex 1",id: 1,placeTypes:[
      {placeTypeId:1,placeTypeName:"ex1.1",
      places:[
        this.deepCopy()
      ]}
    ]},
    {nearByTypeName : "ex 2",id: 2,placeTypes:[
      {id:2,placeTypeName:"ex 2.1",places:[
        this.deepCopy()
      ]},
      {id:3,placeTypeName:"ex2.1.1",places:[
        this.deepCopy()
      ]}
    ]}
  ]

  deepCopy(){
    return ['TRY','USA'].slice(0)
  }

Ensure that the deepCopy function returns an array

template

<div *ngFor="let m of InitialModel">
    {{m.nearByTypeName }}

    <div *ngFor="let type of m.placeTypes">
        {{type.placeTypeName}}

        <div *ngFor="let place of type.places">
            {{place}}
        </div>
    </div>
</div>

View demo

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

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Ways to retrieve time series data using angular

Can someone please advise on the correct Angular technique to retrieve all of the time series data from an API where the keys are unknown, like in this example? Appreciate any help or guidance. Thank you. ...

What is the correct way to specify the data type for the useState hook when I intend to store an array of objects?

My dilemma involves storing an array of objects using the useState hook, but I am struggling with the syntax required to describe the expected type. The type that I want to store is Array<Updates>. Below is the code I have: const [messages, setMessa ...

The NX monorepo from @nrwl is unable to locate the .svgr configuration file within the lib directory

Recently, I started working with NX Monorepo that consists of 2 separate react applications. In order to share icons between these apps, I decided to create an icons library. I made changes to the project.json file of the icons library and added a svg com ...

Issue with blueprintjs/core type in JupyterLab Extension after running npm install

Developed a JLab extension and saved it to Git repository. Established a new environment and successfully pulled the code, which was also verified by a friend. Subsequently, included a new react object to the extension and pushed it back to Git in a fresh ...

Do you have any suggestions for optimizing an Angular 15 reactive form that gets filled with data from an API?

Creating an Angular 15 Reactive Form with FormGroup As I delve into the documentation to construct a form with 4 inputs that are populated with data retrieved via GET requests and then updated upon submission through PUT requests, I find that it is functi ...

How can I create an input field in MUI that restricts input to letters, numbers, and dashes

Is there a way to configure an MUI input field so that it only accepts letters, numbers, and dashes while excluding spaces and symbols such as (*&^%$#@!,.<>{}[])? Specifically, I want to allow characters that wouldn't disrupt a URL, like . Tha ...

Improving efficiency of basic image carousel in Angular 8

In my Angular 8 app, I am developing a basic carousel without relying on external libraries like jQuery or NgB. Instead, I opted to use pure JS for the task. However, the code seems quite cumbersome and I believe there must be a more efficient way to achie ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...

Angular input for date is showing wrong value due to timezone problem

My database stores dates in UTC format: this.eventItem.date: "2023-06-21T00:00:00.000Z" The input form field value is showing '2023-06-20' (incorrect day number), which seems to be a timezone issue. I am located in a region with a +3 o ...

The output decorator in Angular seems to be malfunctioning and displaying an error message

demo.Parent.html <p>demo-parent is functioning!</p> <app-demo-child (property)="parentFunction($event)" ></app-demo-child> demo.parent.component.ts import { Component, OnInit } from '@angular/core'; @Component({ sel ...

Tips for developing a strongly-typed generic function that works seamlessly with redux slices and their corresponding actions

Currently, I am working with @reduxjs/toolkit and aiming to develop a function that can easily create a slice with default reducers. Although my current implementation is functional, it lacks strong typing. Is there a way to design a function in such a man ...

Generic type input being accepted

I am trying to work with a basic generic class: export class MyType<T>{} In the directive class, I want to create an @Input field that should be of type MyType: @Input field MyType<>; However, my code editor is showing an error that MyType& ...

Removing the @Input decorator in Angular's codebase

I am currently working on an Angular project for a class, and I'm facing an issue where removing the @Input decorator from my component is causing the entire application to not load properly. import { Component, OnInit, Input } from '@angular/ ...

Unable to fetch information from the controllerAPI function within the tsx file due to a Module Parse error

I am currently working on fetching records from a database using ControllerApi and displaying them through React. The code snippet below is from a file with a *.tsx extension: import React, { useState } from 'react'; import ReactDOM from 'r ...

What steps are needed to enable WebStorm's autocompletion for external libraries?

As a beginner user of WebStorm and TypeScript, I am currently experimenting with incorporating the libstl library into my code. The snippet below is what I have written so far: var PriorityQueue = require('libstl').PriorityQueue; var queue = ne ...

Encountered an issue with Angular Material sidenav: The synthetic listener @transform.start was found

Click here to visit the StackBlitz link Encountering an issue while attempting to utilize the material side nav. Error message: preview-29b0f46fcc27b310236ab.js:1 ERROR Error: Uncaught (in promise): Error: Found the synthetic listener @transform.start. P ...

Display a customized modal showcasing the data of a particular user

Seeking advice on how to pass data to a modal based on a specific user. I have an array with user information and would like to display their name and email in a modal when the user is clicked on. Any suggestions on how to accomplish this? ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strin ...