Master the art of iterating through an Object in TypeScript

I need help with looping through an Object in TypeScript. While the following examples work in JavaScript, I understand why they pose a problem in TypeScript. Unfortunately, I am struggling to find the correct approach to solve this issue. Am I approaching this problem incorrectly?

My objective is to iterate through a two-level-deep Object and be able to directly access the item from the Object at the end, rather than just its value.

For instance:

interface A {
  abc: number
  acd: number
}
interface B {
  bcd: number
  bde: number
}
interface C {
  cde: number
  cef: number
}
interface Data {
  a: A
  b: B
  c: C
}

const data: Data = {
  a: {
    abc: 1,
    acd: 2
  },
  b: {
    bcd: 3,
    bde: 4
  },
  c: {
    cde: 5,
    cef: 6
  }
}

// Attempting with for-in loop
for (const cat in data) {
  for (const item in cat) {
    console.log(cat, item) // This works fine because both are strings
    console.log(data[cat][item]) // However, 'cat' and 'item' are treated as strings, not keys of Data.
  }
}

// Trying with for-of loop
for (const cat of Object.keys(data)) {
  for (const item of Object.keys(cat)) {
    console.log(data[cat][item]) // Similarly, 'cat' becomes just a string and not a valid key of Data.
  }
}

// Experimenting with forEach method
Object.keys(data).forEach((cat) => {
  Object.keys(cat).forEach(item => console.log(data[cat][item])) // In this case too, 'cat' is considered only a string and not a key of Data
})

Thank you for your assistance :)

Answer №1

Whenever you iterate through Object.keys(anotherObject), remember that you're actually accessing the keys and not the actual objects.

for (let dogKey of Object.keys(info)) {
  for (let productKey of Object.keys(info[dogKey])) {
    console.log(dogKey, productKey)
    console.log(info[dogKey][productKey])
  }
}

Answer №2

While I generally try to avoid using "any", in this particular code snippet, it seems quite safe due to the if statements being used.


Object.keys(data).forEach((key1 ) => {
    if(key1 in data) {
        Object.keys((data as any)[key1]).forEach((key2) => {
            if(key2 in (data as any)[key1]) {
                console.log((data as any)[key1][key2])
            }

        })
    }  
})

Answer №3

Take a look at this:

for (let item of Object.keys(data.a)) {
   console.log(data.a[item]);

By running this loop, you can see all the keys stored in data.a. Each key value can be accessed and manipulated by using data.a[item].

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 is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

Disregard any unrecognized variables associated with the third-party package

I've been working on integrating the bluesnap payment gateway into a react/ts project. I added their hosted javascript code to my public/index.html and started the integration within a component. However, when compiling, an error pops up saying ' ...

What is the best way to ensure all keys of a certain type are mandatory, while still allowing for the possibility of

I am looking to create a mapping of key/value pairs for a specific type in the following way: required_key: string | undefined transformed to required_key: string | undefined (remains the same) required_key: string transformed to required_key: string (rem ...

Redirecting to login on browser refresh in Angular using Firebase's canActivate feature

An Angular 5 authentication application using angularfire2 and Firebase has been developed. The app functions correctly when navigating through in-app links. However, an issue arises when refreshing the browser, as it redirects back to the Login page even ...

When I bring in a component from my personal library, it will assign the type "any" to it

I'm facing an issue when trying to import a component from my own library. The component within the library is actually sourced from another one (so I import the component, customize it, and then export the customized version). However, upon importi ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Unable to impose a restriction on the number input field limit

My input field has a type of "number" with the min and max attributes applied to limit user input. However, I am facing an issue where users can still enter values beyond the set limit. How can I prevent users from entering values above the specified lim ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

Updating array values using radio buttons in Angular: A step-by-step guide

I am creating an array of phone objects where each phone is assigned a role, either main or secondary. I want to be able to update the main phone using a radio button and have it reflect in my object list. Here is my code: HTML <section *ngFor="le ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...

Effectively managing intricate and nested JSON objects within Angular's API service

As I work on creating an API service for a carwash, I am faced with the challenge of handling a large and complex json object (referred to as the Carwash object). Each property within this object is essentially another object that consists of a mix of simp ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Angular Material's dialog modal swiftly closes without delay

Could you please explain why the modal opens and then closes instantly when I click on the Create Project button? https://example.com/edit/angular-code I am trying to display a component within the modal using Angular Material. portafolio.component.ts ...

The member 'pipe' is not found within the 'AngularFireObject<{}>' type

As someone new to Angular, I've been following a tutorial by Mosh Hamedani on version 6 of Angular, but unfortunately the tutorial is based on version 4. Currently, I'm working on an e-commerce project that involves implementing an AddToCart butt ...

What is the best approach for implementing recursion within a foreach loop in TypeScript?

Problem Situation I am attempting to develop a customized typewriting effect similar to the one demonstrated here with a 100ms delay using Angular. The TypeScript code I have written for this purpose is as follows: private arr: string[] = ["Lead Dev ...

Create a d.ts file in JavaScript that includes a default function and a named export

While working on writing a d.ts file for worker-farm (https://github.com/rvagg/node-worker-farm), I encountered an issue. The way worker-farm handles module.exports is as follows: module.exports = farm module.exports.end = end When trying to replica ...

Guide on retrieving an ArrayList() from intricate function in Angular

Simplicity is the key to my question. Let's take a look at this Angular method: getAllOrdersHeaders(){ this.getAllOrdersIds().subscribe(idList=>{ idList.forEach(id=>{ this.ordersCollection.doc(id).collection('metadata&apo ...

A React component featuring a nested map function should always include a "unique key" prop for each element

I am trying to figure out how to assign a proper Key Value in this component: {var.map((building, index) => { const handles = building.buildingVertices.map((point) => { return ( <DrawingHandle key={`${i ...

Can anyone provide a solution for fixing TypeScript/React error code TS7053?

I encountered an error message with code TS7053 which states: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'. No index signa ...