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

Examining the contents of an array in JavaScript

I am currently conducting API testing. My objective is to verify the presence of a specific name within the API response. The data from the API response is structured in an array format. Despite my intention to check for the existence of the name "activ ...

Choose elements within an array in a JSONB dataset

I am trying to extract and process the objects within an array using JSONB in a Postgres database with Groovy. Here is how my JSON data is structured and stored in the database: "playersContainer": { "players": [ { "id ...

The argument type 'string' does not match the parameter type 'keyof Chainable' in Cypress JavaScript

Trying to incorporate a unique custom command in Cypress (commands.js file) as follows: Cypress.Commands.add("login", (email, password) => { cy.intercept('POST', '**/auth').as('login'); cy.visit(& ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

Guidelines for displaying user profile information in the dashboard page through an Angular project, considering the different user types (user, super user, admin)

In my application, I have implemented the dashboard feature. There are three types of dashboards: the regular user dashboard, super user dashboard, and admin dashboard. The super user and admin dashboards include additional tables along with the data from ...

Troubleshooting NameError when Parsing JSON with Python 2.7 and Handling NULL Results

I am attempting to extract the "b" tag from this JSON data but keep encountering a NameError. Any suggestions on how to correct this code? json_data = {"one": null, "two": {"a": "1", "b": null}, "three": "3" } if __name__=="_ ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

InfoWindow from JSON data not displaying in Google Maps V3

My current project involves using PHP to generate a JSON file from data stored in MySQL. One of the goals I have is to display certain pieces of this data in an information window on Google Maps whenever I click on a marker. Although I've managed to ...

Upon running NPM start, an inexplicable error arises when attempting to execute "gulp clean && gulp frontend && gulp dev" in the package.json file

After diligently following the steps outlined in this tutorial, I hit a roadblock at the frontend tasks stage. Upon running NPM with npm start, I encountered the following error: https://i.stack.imgur.com/bvS1e.jpg I identified the issue to be either the ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

What is the process for attaching a key signature onto a string in order for it to function as an index for an object?

How can I specify a signature in TypeScript to indicate that the current value might be used as an index for accessing a specific object? I am encountering the error: Element implicitly has an 'any' type because expression of type 'string&ap ...

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

What is the process for transforming the output of a query into JSON format in Oracle 12c?

In order to update a new column with JSON, it is necessary to convert the selected data into JSON format first. Below is the code that has been modified from the comment: SELECT a.col1 a.col2 b.col3 b.col4 from table AS JSON The desired output format i ...

Mastering the use of the oneOf keyword in JSON Schema can help you customize your JSON file structures by making certain fields optional instead of

My JSON schema is designed to handle disease notification data, specifically focusing on the patient's hospitalization status. If a patient is hospitalized due to contracting the disease, their hospital information must be included in the data. Howeve ...

Start a fresh project using the Teamweek API with jQuery integration

After successfully acquiring the planning details from Teamweek using the API (Get projects from Teamweek in jQuery), I am now looking to feed Teamweek a project. Even though the code below seems to work (based on the response received), I am unable to lo ...

The server responded with an error code (406) Not Acceptable when attempting to Invoke-RestMethod using powershell.exe

After struggling to pass a parameter without receiving error 406 in Jenkinsfile, I finally managed to store the version id from a JSON response in a baseid variable. However, now I am stuck on how to use this baseid inside a PowerShell script as illustrate ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

NSInvalidArgumentException' error: 'Unrecognized selector sent to instance of __NSCFString

Below is the code snippet I am referring to: The nameLabel text attribute is set as the UserFullName from the unknown_object array in dict_Details. And here is my response: The getUserReviewsResponse data shows a status code of 200 and includes an ar ...

Verification process in JSON configuration

Here is a JSON schema example: { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "additionalProperties": false, "properties": { "Payload": { "type": "object", "additionalProperties": ...