Using Typescript to iterate through nested interface data with the `forEach()` method

CountTargetsData serves as an interface for parsing JSON data with multiple levels of nesting, as illustrated below.

interface CountTargetsData {
  data: {
    [state: string]: {
      [date: string]: {
        [index: string]: { [id: string]: { [targets: string]: number } },
      },
    },
  };
}

const parseCounters = useCallback(
  async (responseDeploymentData: CountTargetsData) => {
    //WANT TO PARSE ID AND TARGETS HERE
  }
);

With the complex nested structure, how can I utilize the forEach() method to extract the id and targets values for each entry in CountTargetsData?

Sample Data:

    "stateA": {
        "2016-06-03": [
            {
                "1200": {
                    "count_targets": 1,
                    "count_targets_excluded": 0,
                    "count_targets_pending": 0,
                    "count_targets_in_progress": 0,
                    "count_targets_completed": 0,
                    "count_targets_failed": 1
                }
            }
        ],
        "2016-06-07": [
            {
                "1455": {
                    "count_targets": 1,
                    "count_targets_excluded": 0,
                    "count_targets_pending": 0,
                    "count_targets_in_progress": 0,
                    "count_targets_completed": 1,
                    "count_targets_failed": 0
                }
            }
        ]
         
    }
}

Answer №1

Update

Your provided data does not match the required type structure:

interface CountTargetsData {
  data: {
    [state: string]: {
      [date: string]: ({
        [index: string]: {
          [id: string]: {
            [targets: string]: number
          }
        },
      })[],
    },
  };
}

const data = {
  "stateA": {
    "2016-06-03": [{
      "1200": {
        "count_targets": 1,
        "count_targets_excluded": 0,
        "count_targets_pending": 0,
        "count_targets_in_progress": 0,
        "count_targets_completed": 0,
        "count_targets_failed": 1
      }
    }],
    "2016-06-07": [{
      "1455": {
        "count_targets": 1,
        "count_targets_excluded": 0,
        "count_targets_pending": 0,
        "count_targets_in_progress": 0,
        "count_targets_completed": 1,
        "count_targets_failed": 0
      }
    }]
  }
}

Object.entries(data).forEach(([state, value]) => {
  Object.entries(value).forEach(([date, value]) => {
    value.forEach(obj => {
      Object.entries(obj).forEach(([id, value]) => {
        Object.entries(value).forEach(([target, value]) => {
          console.log(state, date, id, target, value)
        })
      })
    })
  })
})

Old answer

The given nested data requires a different approach than using .forEach directly.

Maybe consider using Object.entries / Object.values first or implementing a for..of loop:

const parseCounters = useCallback(
    async (
      responseDeploymentData: CountTargetsData
    ) => {
      Object.values(responseDeploymentData.data).forEach(state => {
        Object.values(state).forEach(date => {
          // continue logic here
        })
      })
  }
const parseCounters = useCallback(
    async (
      responseDeploymentData: CountTargetsData
    ) => {
      for (const state of responseDeploymentData.data) {
        for (const date of state) {
          // continue logic here
        }
      }
  }

Consider recursion or DFS algorithm for better handling of nested data

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

Twitter Bootstrap Dropdown PHP link fails to function

Recently, I designed a dropdown menu to be used on a PHP page. The main button, which contains the dropdown links, needs to still function as a link to another page. Despite following all the instructions provided on the Bootstrap website, the main button ...

Debating the use of cameras in Three.js

Creating a camera in code typically looks like this: var camera = new THREE.PerspectiveCamera( FOV, ASPECT_RATIO, NEAR_PLANE, FAR_PLANE ); But what exactly do these values represent? ...

Loading V-Select with Data from JSON Using Vue.js

I tried to populate my v-select multiselect element using a JSON object, but unfortunately it did not work as expected. Here is the result I encountered: https://i.sstatic.net/kd1Gl.png <v-select v-model="serviceValues" :items="serviceO ...

Relocate the bxslider carousel to the specific div clicked on

Is it possible to move the slider to the selected div when using bxslider? I have a carousel below. Currently, when you click on the controls (left/right arrows), it only moves one slide/div at a time, keeping the active div always on the left side. Howev ...

Transform percentage into pixels

I'm currently utilizing this specific JavaScript range slider and my goal is to define a minimum and maximum value in pixels, rather than the default percentage range from 0 to 100. I have successfully implemented the min and max settings, now my nex ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

Tips for linking the controls of storybook with manual state updates

I'm a newcomer to storybook and frontend development. Below is the code for my checkbox.tsx component: import React from 'react'; import styles from './checkbox.module.css'; // Make sure this import is correct interface CheckboxP ...

What issues can trailing white space cause in TypeScript coding?

While I understand that linting is the reason for this, why are trailing spaces considered problematic? I plan to disable this feature in tslint.json, but before I make that change, I want to ensure I'm not making a mistake. Visual Studio Code alert ...

Error: Uncaught Type Error - Attempted to access property 'then' of an undefined variable. This issue occurred when attempting to use a

I attempted to use the code below, considering that node operates asynchronously and in order to execute my code sequentially I added a then function. However, I encountered the error TypeError: Cannot read property 'then' of undefined. The code ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

What is the best method for incorporating a JSON framework into a project

I've recently obtained the JSON framework DMG file from http://code.google.com/p/json-framework/downloads/list. I then proceeded to follow Option 3 outlined here: http://code.google.com/p/json-framework/wiki/InstallationInstructions. Initially, I set ...

Angular filtering options based on user input and model selection

In the jsbin demo provided, there is an input field, a select option, and a list of movies. The objective is to filter the list of movies in Angular based on user input in the input field and selection in the select dropdown. <div ng-controller="myCont ...

Modify HTML tags based on the sum of <li> elements using jQuery

I have a dynamic slider with items in a list that will change based on the page. My goal is to create a loop that updates the data-slide-to attribute with the correct slide number for each item. After several attempts, I managed to come up with a solutio ...

Change the name of the interface from the imported type

When working with Google Apps Script, I have implemented the Advanced Calendar Service, originally labeled as "Calendar". However, I have renamed it to "CalendarService". How can I incorporate this name change when utilizing the type definitions for Apps S ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

Angular 6 - Accessing grandparent methods in grandchild components

I am in need of running the functions of the grandparent component: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.cs ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Tips for downsizing a large image to fit into a smaller area

I am working on a page layout that features a small circular navigation element. However, I am facing an issue with fitting a large picture within the boundaries of this small circle without it overflowing and causing alignment problems. Does anyone have ...