Can someone provide guidance on utilizing the map function to iterate through intricate components in TypeScript?

I am facing a challenge while trying to iterate through a complex object containing 'inner objects'. When using the map function, I can only access one level below. How can I utilize map and TypeScript to loop through multiple levels below? Whenever I attempt to use map for the second level, I encounter an error.

The JSON structure is as follows:

{
  "PAYMENTS": [
    {
      "id": 1,
      "userID": 1,
      "month": "March 2015",
      "details": {
        "item1": {
          "amount": "1000",
          "date": "01/03/2015",
          "id": 2
        },
        "item2": {
          "amount": "2000",
          "date": "03/03/2015",
          "id": 3
        }
      }
    },
    {
      "id": 2,
      "userID": 1,
      "month": "April 2015",
      "details": {
        "item1": {
          "amount": "100",
          "date": "01/04/2015",
          "id": 1
        }
      }
    }
  ]
}

I have defined two interfaces:

export interface IPaymentDetailEntity {
  id: number;
  date: Date;
  amount: string;
}

export interface IPaymentEntity {
  id:number;
  month:string;
  userID:number;
  details:IPaymentDetailEntity[]
}

To iterate through the objects, I am attempting the following:

{payments.map(paymentDetails => (
  <div key={paymentDetails.id}>
    {paymentDetails.month} {paymentDetails.userID}
    {/* This part is causing an issue */}
    {paymentDetails.details.map(item => (
      <div key={item.id}>
        <span>{item.date}</span>
        <span>{item.amount}</span>
      </div>
    ))}

Answer №1

details is now an object instead of an array, so update details:IPaymentDetailEntity[] to details:IPaymentDetailEntity in the IPaymentEntity interface.

Modify

   export interface IPaymentEntity {
        id:number;
        month:string;
       userID:number;
       details:IPaymentDetailEntity[]
   }

To

  export interface IPaymentEntity {
        id:number;
        month:string;
       userID:number;
       details:IPaymentDetailEntity
   }

You can then use Object.keys to iterate through the details object and .map on it to retrieve id, date, and amount of items as shown below

   {payments.map(paymentDetails => (
    <div key={paymentDetails.id}>
         {paymentDetails.month} {paymentDetails.userID}
        {paymentDetails.details && Object.keys(paymentDetails.details).map(detail=> (
          <div key={paymentDetails.details[detail].id}>
              <span>{paymentDetails.details[detail].date}</span>
              <span>{paymentDetails.details[detail].amount}</span>
         </div>
     ))}

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 are the best ways to utilize @types/bootbox and @types/jquery?

Is there a way to incorporate @types/bootbox and @types/jquery into an Angular 4 project? I attempted the following: npm install @types/bootbox and in my code, I am implementing it like so: import * as bootbox from 'bootbox'. However, I encou ...

Filter data in GraphQL based on specific key values, such as restricting users to be exactly 31 years old

I'm currently delving into the world of GraphQL and encountered a simple problem that I can't seem to find a solution for in any documentation. All I want to do is fetch a list of users from a JSON dataset where their age is specified as 31. Ini ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

What is the method for activating a validation of a child component from a parent component during the submission process in Angular 4

I have a scenario where I have multiple child form components included in a parent component. Each child component contains its own form group, and I need to validate all child forms when the user clicks on submit in the parent form. How can I trigger val ...

converting HTML data to JSON format

Here is a basic example to consider: import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup df = pd.DataFrame({'link' : ['https://en.wikipedia.org/wiki/World%27s_funniest_joke', ...

Develop a customized configuration module for managing ESLint, Prettier, and resolving import issues efficiently

Currently, I am developing a configuration npm module for my personal project. This repository includes Prettier, ESLint, tsconfig, and other tools that I have set up. You can find my configuration tools repository here: https://github.com/Seyrinian/seyri ...

Unable to retrieve data following a promise in Ionic 3

Hello, I'm currently working on an Ionic application that needs to display data in a Form Group after retrieving it with a SOAP ReadData request. Although I call my function and try to display the data in the form, there seems to be an issue as the f ...

By utilizing custom typeRoots while continuing to export these types alongside the entry point

For my project setup, I employ rollup to bundle an associated index.d.ts (and index.js) for the entrypoint src/index.ts. Within the project structure, there exists a directory named src/types containing multiple .d.ts files. These types are globally acces ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

Upon successfully maneuvering vendors who fail to load the NEXT.JS Link

Here is an image that is not displaying properly. The navbar's responsiveness seems to be causing the issue. return ( <Link key={index} href={'/'+item.id} > <li className="nav-item dropdown position-stati ...

What is the best method to terminate an Electron application using TypeScript?

I have been searching for the proper method to close an Electron app. My app uses React and TypeScript. After coming across this helpful post, I discovered a working solution: const remote = require('electron').remote; let w = remote.getCurrentW ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

When integrating the @azure/msal-angular import into the Angular application, the screen unexpectedly goes blank,

Starting a new Angular app and everything is rendering as expected at localhost:4200 until the following change is made: @NgModule({ declarations: [ AppComponent, HeaderBannerComponent, MainContentComponent, FooterContentinfoComponent ...

How can I retrieve the position of a node in rapidjson?

I'm using rapidjson to deserialize a JSON string into an object. However, when there are issues with the content rather than the structure of the JSON, I want to be able to report an error indicating the offset where the problem occurs. The challenge ...

Having trouble accessing the JSON result with Jquery

My controller has an action that returns JSON results, which I have tested and confirmed to be working properly. public JsonResult GetProductsByDepList(int id) { JsonResult jr = new JsonResult(); var _product = from a in DataContex ...

Why is it important to incorporate depth in JSON encoding?

Take a look at this illustrative code: $array = array( 'GiamPy' => array( 'Age' => '18', 'Password' => array( 'password' => '1234&apo ...

I am having trouble getting debugging with source maps to work in VSCode and Browserify

I'm currently experiencing an issue with setting breakpoints in Chrome using VSCode, especially when working with TypeScript and Browserify. Oddly enough, if I open Chrome separately and manually refresh the page, the source maps load correctly and I ...

What are the differences between Modules and Typings in Typescript?

I have been searching far and wide for information on the variances between modules and typings in TypeScript, but I'm still struggling to grasp the concept. As a newcomer to TypeScript, could someone please provide a concise explanation of these diff ...

Innovative approach for showcasing JSON array using checkboxes

I have created a multidimensional array using JSON. However, now I am facing the challenge of organizing groups of checkboxes in a visually appealing manner, such as separating them with horizontal bars or placing them into tables. Here is an example of t ...

What is the best way to insert a new value into an already existing JSON array?

My JSON structure looks like this: { "intents": [ { "tag": "greeting", "patterns": [ "Hi there", "How are you", ...