TypeScript Interface for intricately nested array arrangement

I am brand new to Typescript and have been able to make progress in various areas, but I'm struggling with creating interfaces for deeply nested objects containing "taskName" and "totalTaskHours". The data structure is as follows:

[
    {
      "20229622": [
        {
          "taskName": "Project Management",
          "totalTaskHours": "1589.4"
        },
        {
          "taskName": "Marketing",
          "totalTaskHours": "1306.8"
        },
        {
          "taskName": "Design",
          "totalTaskHours": "212.4"
        },
        {
          "taskName": "Programming",
          "totalTaskHours": "415.8"
        }
      ]
    },
    {
      "20229623": [
        {
          "taskName": "Project Management",
          "totalTaskHours": "980.1"
        },
        {
          "taskName": "Marketing",
          "totalTaskHours": "717.3"
        },
        {
          "taskName": "Design",
          "totalTaskHours": "468.9"
        }
      ]
    },
    {
      "20229624": [
        {
          "taskName": "Programming",
          "totalTaskHours": "5930.1"
        },
        {
          "taskName": "Project Management",
          "totalTaskHours": "997.2"
        },
        {
          "taskName": "Marketing",
          "totalTaskHours": "2108.69"
        },
        {
          "taskName": "Design",
          "totalTaskHours": "529.2"
        }
      ]
    }
  ]

Despite my attempts to access the deeply nested objects within the array, I keep encountering errors.

missing_other_nested_objects

I've tried defining interfaces like this (which obviously didn't work):

interface TaskItem {
  taskName: string;
  totalTaskHours: string;
}

interface TaskItemArray {
  [key:string]: {
    [key:string]: TaskItem[];
  };
}
interface TaskBreakdownSummedByCategory {
  [key:string]: TaskItemArray[];
}

I also attempted the following, but the data structure was too shallow:

interface TaskItem {
  taskName: string;
  totalTaskHours: string;
}
interface TaskBreakdownSummedByCategory {
  [key:string]: TaskItem;
}

Could someone quickly provide some assistance with this issue? I'm still learning and the basic tutorials I've found don't cover deep nested objects. Thanks!

Answer №1

You are really on the right track. Instead of specifying the overall array type as TaskItemHolder[], you can define the type of its elements directly within the outer array structure like this:

interface TaskItem {
  taskName: string;
  totalTaskHours: string;
}

type TaskItemHolder = { [key: string]: TaskItem[] }[];

const data: TaskItemHolder = [
  {
    "220229622": [
      { "taskName": "Project Management", "totalTaskHours": "1589.4" },
      { "taskName": "Marketing", "totalTaskHours": "1306.8" },
      { "taskName": "Design", "totalTaskHours": "212.4" },
      { "taskName": "Programming", "totalTaskHours": "415.8" }
    ]
  },
  {...}
];

If you need to loop through this data structure, you may encounter challenges due to its nested object format. You could use methods like Object.keys(...)[0] or Object.entries(...) to access the inner objects and iterate over them. Here's an example:

for (const holder of data) {
  const key = Object.keys(holder)[0];
  console.log("Holder with key " + key + ":");
  for (const entry of holder[key]) {
    console.log(entry.taskName);
  }
}

A better approach would be to reconsider the structure to avoid the need for such complex looping. However, if you must work with the current format, using methods like Object.entries() can simplify the process:

for (const holder of data) {
  for (const [key, value] of Object.entries(holder)) {
    console.log("Holder with key " + key + ":");
    for (const entry of value) {
      console.log(entry.taskName);
    }
  }
}

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

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

How can a div be displayed next to another div when it is clicked using angular2?

Is there a way to have another page show up after clicking on a div, like shown in the image below? Before Click: https://i.sstatic.net/qSBbc.png After Click: https://i.sstatic.net/julH4.png ...

Learn how to access values from appsettings.json in Typescript files using Angular 2

Currently, I am working with Angular 2 and have my appsettings.json structured as shown below: "Dummies": { "Neck": "test,test1", } I would like to know how to retrieve the value of Neck in a TypeScript file. Can you help me with this? ...

Compiling Vue with TypeScript: Troubleshooting common errors

Using Vue Components with Templates Multiple Times in TypeScript I am working on utilizing a component with a template multiple times within another component. The code is split between a .html file and a .ts file. The .html file structure is as follows: ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

What is the best way to retrieve response data from an http request in Angular?

I am looking to retrieve a response from a GET HTTP request, and my server is written in JavaScript. The specific part where I send a response is as follows: app.get('/getReport',function(req,res) { try { const data=fs.readFileSync('./ ...

Navigating any object array in TypeScript and retrieving its properties

Consider the following JSON data object: var dataObjects = [ { "Name": "Date & Time", "Type": "Date", "Value": "2019-12-11" }, { "Name": "Activity", "Type": "String", ...

Guide on tracking the cursor using Angular

Recently, I developed a basic application in Angular that incorporates animations. You can check out the StackBlitz here to see it in action. The app features states that we can switch to control where an eye is looking. Currently, I am looking for a way ...

Use the ngFor directive to iterate over the most recently created array from the parent ng

I am looking to link material tabs with ngFor to generate arrays for child ngFor. Let's start from the beginning: <mat-tab-group> <mat-tab *ngFor="let tab of asyncTabs "> <ng-template mat-tab-label>{{tab.label}}</ng-template ...

How to bring in a specific module using its name in TypeScript

Can a module in typescript import itself by its own name? For example, let's consider a module called my-module with various tests. Is it possible to import it within the tests using import ... from "my-module" instead of using a local path like impo ...

Issue when calling .create() method on Mongoose schema: "this expression is not callable" error in TypeScript

Encountering an error with the .create method on a mongoose model in Next JS while making a call in an API route. The get request is functioning properly... The structure: pages>API>task.tsx import dbConnect from "../../util/dbconnect"; im ...

How can I effectively integrate TypeScript with Jest to mock ES6 class static properties?

For the purpose of simulating payment failures in my Jest tests, I have developed a mock file for mangopay2-nodejs-sdk: // __mocks__/mangopay2-nodejs-sdk.ts import BaseMangoPay from 'mangopay2-nodejs-sdk'; export default class MangoPay extends B ...

Is it possible to utilize Angular without the need for Node.js?

In our project, we have been utilizing Django as our server framework and incorporating JavaScript for client-side scripting. As we transition to Angular4, we are considering the necessity of running a separate node.js server alongside our current Django ...

What is the method for initializing an HTMLElement variable outside of a function in an Angular component.ts file?

I am facing an issue where I want to declare HTMLElement variables accessible to all functions within a particular class. Despite my efforts, declaring it before the constructor and assigning its value inside the constructor is not working as expected. Str ...

Angular Error: Trying to access a property on an undefined variable

I'm currently having an issue with assigning data from an API to my Angular component file. Whenever I try to assign the data to my object variable, I receive an error stating: "cannot set property of undefined." Below is the relevant code snippet: C ...

I find myself hindered by TypeScript when trying to specify the accurate constraints for getUserMedia

I'm having difficulty getting a screen to stream within my Angular 5 Electron application. I am utilizing the desktopCapturer feature provided by Electron. Below is an excerpt of my code: loadCurrentScreensource() { desktopCapturer.getSources({ ...

Transform Loopback 4 filter into a SQL WHERE condition

When using Loopback 4, the filter object that is received by functions like Get and Count appears as shown below: { where: { property: { op: value; } } } I am interested in converting this structure into an SQL WHERE clause to use it in ...

Transforming the api response object into a map containing nested maps with string values

Is there a way to optimize the code below without using loops? Although I prefer not to use loops in my code, the current implementation relies on them. I'm curious if achieving the same result is possible with a different approach. Code: ts private ...

An illustration of object destructuring using multiple arguments in rest notation

Here's a snippet of code that I've been working on: onFilterChange = ({name}: {name: string}) => { console.log(`entered onFilterChange and name is ${name}` ); } When there's only one argument, everything runs smoothly. However, whe ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...