Having trouble looping through a Map object converted from a JSON in TypeScript/Angular

Having recently delved into the world of TypeScript and Angular with a strong background in Java and Kotlin, I encountered a puzzling issue while working on a class.

export interface GeoData {
    allregions: Map<string, string>;
}

This class was designed to parse the following JSON data:

{"allregions":{"whatever":"WHT","a region":"ARE","something":"SMT"}

The JSON data was successfully retrieved from a file using HttpClient.get() and upon inspection through debugging, the content appeared as expected. For instance, this code worked:

console.log(data.allregions["whatever"])

It correctly displayed WHT.

However, when attempting to iterate over the 'allregions' map using a forEach loop like this:

data.allregions.forEach((value: string, key: string) => {
        console.log(key, value);
    });

An error message stating that "

data.allregions.forEach is not a function
" was thrown. Furthermore, trying to retrieve the size or length of the map using size or entries.length resulted in unexpected output or errors.

This unexpected behavior led me to wonder: what exactly is happening here?

Answer №1

It appears that you are using forEach on an object. You can achieve the desired result by combining Object.keys() and forEach()

var data = {"countries":{"USA":"United States","CAN":"Canada","MEX":"Mexico"}}
Object.keys(data.countries).forEach(function(key) {
  console.log(`key: ${key}, value:${data.countries[key]}`);
});

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

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

Improving the process of class initialization in Angular 4 using TypeScript

Is there a more efficient method to initialize an inner class within an outer class in Angular 4? Suppose we have an outer class named ProductsModel that includes ProductsListModel. We need to send the ProductId string array as part of a server-side reque ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

How can I convert JSON data from an array to an array of objects using JavaScript?

My goal is to load data into an ag-grid. I have obtained the json data in the following format: {"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}} In order to pass it to the grid, I need to transform it to this format: {"my_data":[{"labels" ...

What are the steps for adding a JSON file to a GitHub repository?

Could someone lend a hand with my GitHub issue? I recently uploaded my website to a GitHub repository. The problem I'm facing is that I have a JSON file containing translations that are being processed in JavaScript locally, and everything works fine ...

Combining Kafka as the source with mqtt and using jdbc as the sink

I am using Kafka and have configured a MQTT broker as the data source. The JSON configuration for this setup is as follows: { "name": "mqtt-source", "config": { "connector.class": "io.confluent.connect.mqtt. ...

Creating an ESNext JavaScript file and integrating it into an Angular 2 project: A comprehensive guide

I am facing an issue with my js file named UserService.js and source.js, which has been transformed using transformer typescript. My objective is to integrate this transformed js file into Angular. UserService.js import { Source } from "./source" ...

Deliver an Angular 2 project using a static directory secured with Spring Security

I have successfully set up a frontend using Angular2 and a backend with Java. Currently, I am serving my index.html from the static folder along with other frontend resources. However, upon adding Spring Security to the backend using the @EnableWebSecurity ...

How can we efficiently load a JSON file from a local path into an HTML document in a way that is compatible with all browsers?

I am attempting to retrieve JSON data from a local path and display it on a basic HTML page. I have tried various methods such as fetch, ajax in order to load the data and update the corresponding values on the web page. The goal is to host this page so t ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...

Synchronizing Headers in the Angular PDF Viewer Control by Syncfusion

We implement token-authentication on our endpoints and I am interested in using the standard approach provided by Syncfusion for viewing a PDF. My main concern is whether it's feasible to include headers with the request. Although I have posted this q ...

Sending various kinds of generic types to React component properties

Currently, my team and I are working on a TypeScript/React project that involves creating a versatile 'Wizard' component for multi-step processes. This Wizard acts as a container, receiving an array of 'panel' component properties and p ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

Troubleshoot: Issue with injecting external component into another component using directive in Angular 2

I need the child component template to be loaded into the parent component template. (calling them child and parent for simplicity) Here is the child component: import {Component,Directive, ElementRef, Input} from '@angular/core'; import {IONIC ...

When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map. map = new Map<string, string[]>(); this.effectivitiesList = this.trimEffectivities.split(","); for (let ...

creating a distinctive JSON data structure in Node.js

I have a JSON dataset that looks like this, var data = [ { _id: 5abb46b060808f3a2096f91d, patient_name: 'krishnaaaannnn', gender: 'male', charge_id: 5ab243ac73959deb3ad79fec, description: 'suffering from pain' ...

Running the serve command necessitates being within an Angular project environment; however, despite this, Angular 4 was unable to locate a project definition

I recently cloned an old project from Github and ran into some vulnerabilities when trying to install node_module. In order to address these issues, I executed the following command: npm audit fix Despite running the above command, there were still unres ...

Switching from MOCK API to real API in Angular: The step-by-step guide

I am a beginner in Angular and I am currently working on connecting a sample app to my API gateway called ContactApp. Right now, it is functioning with a mock API but I want to switch to using a real API server. I followed all the steps from a tutorial on ...

Expecting the parameter in get_object_vars() function to be an object, but instead a string was provided

Encountered this issue: login: demo password: **** [AJAX] Invalid JSON - Server response is: <br /> <b>Warning</b>: get_object_vars() expects parameter 1 to be object, string given in <b>C:\wamp\www\examples\ ...

What are the steps to effectively utilize npm warnings within tslint?

After using eslint for javascript files, I am now transitioning to tslint for TypeScript linting. With eslint, I could specify some errors as NPM warnings, such as console logging. https://i.sstatic.net/BNhy6.png I realize that my "warnings" are generat ...