What is the best way to cycle through this information in TypeScript?

My goal is to loop through all the objects stored in the "testmaps" data structure.

I attempted to iterate through "testmaps" initially, but it seems like instead of iterating through maps, I am looping through strings. This prevents me from accessing the nested objects properly.

JSON

{"testmap1":

[{"name":"testObject1","boolean1":true,"boolean2":true,"boolean3":false,"otherString":"test"},
{"name":"testObject2","boolean1":false,"boolean2":false,"boolean3":false,"otherString":"test2"}],

"testmap2":

[{"name":"testObject3","boolean1":false,"boolean2":false,"boolean3":false,"otherString":"test3"},
{"name":"testObject4","boolean1":false,"boolean2":true,"boolean3":false,"otherString":"test4"}]}

TypeScript code for reading the data:

ngOnInit() {

    this.http.get('http://myURL').subscribe(
      data => {
        this.array = data;
        console.log(this.array);
      },
      (err: HttpErrorResponse) => {
        console.log(err.message);
      }
    );
  }

This is how I tried to iterate in TypeScript:

ngDoCheck(){

    for (let map in this.array) {
      for (let item in map.valueOf){
        console.log(item.otherString);
      }
    }
  }

However, the loop I implemented doesn't produce any results.

Answer №1

Using <code>for (let item in data)
enables looping through the properties within an object, iterating to return a key for each property. However, when dealing with arrays, it's more appropriate to utilize forEach() to loop through each individual element.

let data = {
  "testmap1":

    [{
        "name": "testObject1",
        "boolean1": true,
        "boolean2": true,
        "boolean3": false,
        "otherString": "test"
      },
      {
        "name": "testObject2",
        "boolean1": false,
        "boolean2": false,
        "boolean3": false,
        "otherString": "test2"
      }
    ],

  "testmap2":

    [{
        "name": "testObject3",
        "boolean1": false,
        "boolean2": false,
        "boolean3": false,
        "otherString": "test3"
      },
      {
        "name": "testObject4",
        "boolean1": false,
        "boolean2": true,
        "boolean3": false,
        "otherString": "test4"
      }
    ]
};

for (let testmap in data) {
  data[testmap].forEach(item => {
    console.log(item.otherString);
  });
}

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

Adjust the alignment of divs in Angular

In developing a dashboard, I have successfully displayed key value pairs in a component by retrieving them from an environment.ts file. Now, I am looking to rearrange the positioning of the individual testcard components to align with a specific layout sho ...

I am hoping for the bootstrap collapse feature to automatically close one section when another is expanded

I tested this code and it worked for me, but when I try to use it in Angular, I encounter an error in jQuery stating that "collapse tag is not found in jQuery". Can anyone assist me in resolving this issue? $('.button-click').click( function(e ...

Is there a method to categorize an array of objects by a specific key and generate a new array of objects based on the grouping in JavaScript?

Suppose I have an array structured like this. It contains objects with different values but the same date. [ { "date": "2020-12-31T18:30:00.000Z", "value": 450 }, { "date": "20 ...

Why is the 'as' keyword important in TypeScript?

class Superhero { name: string = '' } const superheroesList: Superhero[] = []; const superheroesList2 = [] as Superhero[]; As I was exploring TypeScript, I stumbled upon these two distinct methods of declaring an array. This got me thinking w ...

What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces: DataModel.ts export interface Entry{ id: number, content: Note } export interface Note{ message: string } These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries: DataService.ts getE ...

The SQL database is storing data with a timestamp of January 1st, 0001 at 12:00:00 AM

Working with date/time in ASP.NET Core can be challenging, especially for new users. I have an HTML form with fields that initially appear like this: https://i.sstatic.net/eTAdQ.png The code for the Date Joined and Last Changed fields is as follows: < ...

Unexpected Union Type Return from Apollo Server

When I call my resolver to return a union type (either a User or an object with a message key and value of type String, such as my UserNotFoundError type), it always comes back with "__typename": "User". Why is this happening and how ca ...

Can someone please explain the process of including options in a dropdown menu using Angular 2?

In my dropdown menu, I have the months of the year translated using a pipe syntax like this: {{'January' | translate}} I am looking to bind these translated months in my dropdown. Below is the HTML and the object containing the months: <sele ...

Error message: When attempting to redirect to another route, there is a type error with 'this' as it is implicitly assigned the type 'any'

I'm facing an issue with a component I've built using hooks. I want it to redirect to a different route when a function is called and the server response is received. However, my TypeScript is throwing an error: Type error: 'this' impl ...

The npm package has been successfully installed, but VS Code is having trouble locating it

Currently, I am in the process of developing a simple npm package known as type-exception using TypeScript. After successful test runs and publication on NPM, I have been able to install it into another project (project B). However, upon importing it as a ...

Utilizing the spread operator in Typescript interfaces: best practices

I have a react component that includes the spread operator operating on ...other and passed down to lower levels of the component. interface ButtonProps { colourMode: string; regular: boolean; buttonText: string; disabled?: boolean; iconSize?: st ...

How can one retrieve the selected value from a dropdown menu in Angular?

Objective: My goal is to create a dropdown menu where users can select a value, which will then dynamically change the address of the website based on their selection. Issue: Although I managed to make the address change upon selection, it did so for ever ...

Encountering difficulties during the installation of Angular 6.0.8

We encountered an error during the Angular installation process which resulted in Angular not being installed correctly. D:\software\node-v8.11.2-win-x64>npm install -g @angular/cli D:\software\node-v8.11.2-win-x64\ng -> ...

When using TypeScript, the ReactDOM.render function may not accept certain components

Summary In my TypeScript and React project, I have created the AppContainer.tsx component and exported it as default. In the file app.ts, where I am using ReactDOM to render it on the targeted dom element, I encounter some errors (refer to the image). For ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

What is the best way to emphasize a selected row in a table when clicked using both Bootstrap 4 and Angular 6?

My Bootstrap table is styled with table-hover and all functions as expected. The .table-hover class activates a hover effect on table rows within a <tbody>. Additionally, I have implemented the following method: listClick(event, newValue) { this ...

Steps for converting an object of the Map type to a string

class sample{ title : string items : Map<string,string> =new Map() constructor(){ this.title='Sunny' this.items.set('fruit','Apple') } } var s = new sample() console.log(s) console.log(JSO ...

Exploring the possibilities of combining the latest features in RxJS through refactoring

Currently working on updating my codebase from rxjs 5.x to rxjs 6 and Angular 6. The code I'm focusing on involves initiating a search: startAt = new Subject(); endAt = new Subject(); startobs = this.startAt.asObservable(); endobs = this.endAt.asObs ...

Identifying Labels for the Mean stack within a Database

In the process of developing a compact app using the MEAN stack (Mongo + Express.js + Angular4 + Node.js) for a basic application. Creating a database collection for users and here is an example record/document: { "firstName": "John", "lastName ...

Utilizing a custom asynchronous validator in Angular 8 that returns a Promise or Observable for validation purposes

I am currently working on developing a custom async validator for my registration form. The purpose of this validator is to verify if an email is valid or not by utilizing a third-party API. Here is the reference link to the API website - My approach invo ...