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

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

Easily Organize Your Data with Kendo React Grid: Rearrange Columns and Preserve Your Custom Layout

Currently, I am working on implementing a Kendo React grid with the option set to reorderable={true} for allowing column reordering. However, I am facing difficulty in determining how to save the new order of columns. Which event should I use to detect whe ...

What is the best way to integrate Sass into a Create-React-App project that is using TypeScript

After setting up a new project using create-react-app and typescript, I included a sass file in my project as per the documentation (which mentioned built-in support for sass files). However, when trying to compile, I encountered the following error relate ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

Can a custom subscribe() method be implemented for Angular 2's http service?

Trying my hand at angular2, I discovered the necessity of using the subscribe() method to fetch the results from a get or post method: this.http.post(path, item).subscribe( (response: Response)=> {console.log(response)}, (error: any)=>{console.l ...

NodeJS on Cloudlinux requires that the node modules for applications be stored in a distinct folder (virtual environment) designated by a symbolic link known as "node_modules"

I recently encountered an issue while trying to deploy my Nodejs/TypeScript web application on my cpanel shared hosting. The error I received stated: * Cloudlinux NodeJS Selector requires the node modules for the application to be stored in a separate f ...

Typical approach to receiving a transformed object from an HTTP service

One of the services I provide includes a method with the following implementation: public fetchCrawls(page: number): Observable<ICrawl[]>{ return this._http.get(this._crawlsURL + page) .map((res: Response) => { ...

The left-hand operator in Typescript is not valid

I am a beginner in typescript and I have been following a tutorial called Tour of Heroes on Angular's website. In the final chapter of the tutorial, when I tried to use HTTP with the provided code, everything seemed to run fine but I encountered an er ...

Define a distinct routing parameter that can be accessed through the ActivatedRoute instance

While working on setting up a router in my application, I encountered the need to define a query parameter that must be retrievable through the ActivatedRoute for compatibility reasons. Recently, I had to create some new sub-routes that do not follow the s ...

Observing fluctuations in variable values within Angular2

How can I track changes in a variable bound to an input type text? I attempted using Observables, but the change event is not being triggered. Does anyone have an example or documentation on this? ...

Dynamic form groups in Angular: Avoiding the issue of form inputs not binding to form groups

Purpose My goal is to develop a dynamic form in Angular that adjusts its fields based on an array received from the backend. For example, if the array contains ["one", "two", "three", "four"], the form should only ...

Using ngIf to validate an empty string in Angular 5

I need assistance with validating an empty string retrieved from a server Although it is usually straightforward, it's just not working as expected <div class="ui-g-2 info-txt" *ngIf="appointment.Notes !==null || appointment.Notes !== ...

Before the service call finishes, Akita queries this.selectAll and returns an empty list

Here is the code snippet from my file named widgetquery.ts: @Injectable({ providedIn: 'root' }) export class WidgetQuery extends QueryEntity<WidgetState, WidgetTO> { public Widget$: Observable<WidgetTO> = this.selectActive().filter( ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...

Display the dynamic change of minutes and seconds every second on an Ionic HTML page

I created a JavaScript countdown counter that displays minutes and seconds using the following line of code: document.getElementById("demo").innerHTML = Number(this.minutes) + 'm' + Number(this.seconds) + 's '; However, on iOS devices ...