Loop through a collection of map instances in TypeScript

In my TypeScript code, I am making a call to an API method in a Java class that returns a list of maps.

The TypeScript file includes the code snippet below. When attempting to retrieve data from dataBody, it displays as [Object Object]. I need assistance with modifying the TypeScript code to properly extract the dataset from the Java class.

*public populatePeople(hyperfindId: number) {
            this.getGridInstance()
            //this.peopleList= [];
            this.personIds = [];
            this.personNameById = new Map<string, string>();  
            this.pokerEntryService.getPeopleByHyperfind(hyperfindId, this.tbSite, this.tbDivision, this.tbDepartment).subscribe((data)=>{
                                 
                    let dataBody = JSON.parse(JSON.stringify(data.body));
                    
                    //Need to retrieve data here.
                    
                    if(dataBody.maxExceeded === true){
                           this.showError = true;
                           this.alertService.createAlert('WARNING', this.edapLocaleConvertor.convertLocaleMessage('peopleEditor.maxPeopleExceeded'));       
                    }
             },
             err => {
                    this.showErrorMessage(err);
             });
        }**
     

Java class:

    public List<Map<String,String>> getPeople(Long hyperfindId, String site, String division, String 
   department, LocalDate startDate, LocalDate endDate, String tenantId, String transactionId) {
        Map<String, String> headersMap = new HashMap<String, String>();
        headersMap.put("Authorization", edapRequestContextService.getAccessToken());
        headersMap.put("appKey", GamingPropertiesLoader.getTenantPropertyValue(tenantId,PropertyConstants.APP_KEY, transactionId));
        headersMap.put("Content-Type", EdapConstants.CONTENT_TYPE_JSON);
        //String buildPrimaryOrg = "/Organization/"+site+"/"+division+"/"+department;
        String buildPrimaryOrg = "Organization/United States/Metropolitan Plant/Shipping";
        
        String debugMsg = "buildPrimaryOrg...." + buildPrimaryOrg;
        
        logger.error(TenantContext.getTenantId(), debugMsg, Constants.TOKE_POOL, transactionId);
        
        String requestBody = "{"
                            + "\"select\": "
                            + "["
                                + "{\"alias\": \"PersonId\",\"key\": \"PEOPLE_PERSON_ID\"},"
                                + "{\"alias\": \"PersonNum\",\"key\": \"PEOPLE_PERSON_NUMBER\"},"
                                + "{\"alias\": \"CoreOrgJob\",\"key\": \"EMP_COMMON_PRIMARY_ORG\"},"
                                + "{\"alias\&\quot;primary job\",\"key\": \"EMP_COMMON_PRIMARY_JOB\"}"
                            + "],"
                            + "\"where\": "
                                + "[{\"key\": \"EMP_COMMON_PRIMARY_ORG\",\"alias\": \"CoreOrgJob\","
                                + "\"operator\": \"IN\","
                                + "\"values\" : [\""+buildPrimaryOrg+ "\"}],"
                            + "\"from\": {"
                                + "\"view\": \"EMP\","
                                    + "\"employeeSet\": {"
                                            + "\"dateRange\": "
                                            + "{"
                                                + "\"symbolicPeriod\": {\"id\": \"1\"}"
                                            + "},"
                                            + "\"hyperfind\": "
                                            + "{"
                                                + "\"id\": \"2\""
                                            + "}"
                                    + "}"
                            + "}"
                        + "}";
        
        ResponseEntity<?> response = gamingRestService
                .doPost(tenantId, GamingPropertiesLoader.getTenantPropertyValue(tenantId, PropertyConstants.WFD_API_HOST, transactionId)
                        + Constants.PERSON_MULTI_READ_COMMONS_URI, headersMap, requestBody, String.class, GamingPropertyConstants.REST_GET_PEOPLE_BY_HYPERFIND_ID, transactionId);  

            
        List<Map<String,String>> peopleList =  new ArrayList<>();
        
        JSONObject json = new JSONObject(response.getBody().toString());        
        json = json.getJSONObject("data");      
        JSONArray jsonArray = json.getJSONArray("children");
        
        for(int i=0; i<jsonArray.length(); i++) {
            JSONObject attributesData = jsonArray.getJSONObject(i);
            
            JSONArray attributesArray = attributesData.getJSONArray("attributes");
            
            Map<String,String> m1 = new HashMap<String,String>();
            for(int j=0; j<attributesArray.length(); j++) {
                JSONObject pData = attributesArray.getJSONObject(j);

                debugMsg = "personData:...." + pData.getString("value");
                logger.error(TenantContext.getTenantId(), debugMsg, Constants.TOKE_POOL, 
                transactionId);

    
                m1.put(pData.getString("key"), pData.getString("value"));
                peopleList.add(m1);
            }
        }
        debugMsg = "peopleList size:...." + peopleList.size();
        logger.error(TenantContext.getTenantId(), debugMsg, Constants.TOKE_POOL, transactionId);

        return peopleList;
    }
 

Answer №1

The issue has been successfully resolved by converting the hashmap to an object in order to properly process the values. Everything is now functioning as expected.

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

Setting up nginx docker image to host an angular application while also enabling page refresh is a straightforward process. Here

After reviewing numerous instances of individuals suggesting to simply paste location / { try_files $uri $uri/ /hockey/index.html =404; } or location / { try_files $uri $uri/ /index.html =404; } ...or experimenting with different ...

Infinite loop caused by Angular navigation within route guarding

The routes in my application are configured as shown below: {path: '', redirectTo: 'login', pathMatch: 'full'}, {path: 'todos', component: TodosComponent, canActivate: [AuthGuard]}, {path: 'add-todo', ...

What is the best way to determine if a user is currently in a voice channel using discord.js?

Is there a way for me to determine if a user is currently linked to a voice channel? I am trying to implement a command that allows me to remove a user from a voice channel, and here is how I am attempting to check: const user: any = interaction.options.ge ...

Error TS2694 is being caused by Electron Typescript Material-UI withStyles because the namespace "".../node_modules/csstype/index"" does not have an exported member called 'FontFace'

While I am experienced with Material-UI, I am relatively new to Electron and using React, TypeScript, and Material-UI together. Recently, I encountered an error while attempting to create an electron boilerplate code for future project initialization. Init ...

Navigating through the keys of a parameter that can assume one of three distinct interfaces in TypeScript: a guide

Here is a function example: function myFunc(input: A | B | C) { let key: keyof A | keyof B | keyof C; for(key in input) { let temp = input[key]; console.log(temp); } } The definitions for A, B, and C are as follows: interfa ...

Dealing with errors within nested requests while using switchMap with RxJS

I am faced with a situation where I need to make 2 dependent API calls: the getCars call requires the user id obtained from getUser. There is a possibility that a user may not have any cars, resulting in a 404 error from the API. How can I handle this sc ...

Guide on Implementing a Function Post-Rendering in Angular 2+

I'm looking to implement some changes in the Service file without modifying the Component.ts or directive file. Here's what I need: 1) I want to add an event listener after the service renders its content (which is generated by a third-party tool ...

Angular - utilizing subscription within a for-loop to determine completion

Below is the code I am using to generate sticky notes: update() { this.tab3Service.updateStickyNote(this.stickyNoteUserConnection.stickyNote).subscribe(response => { const updatedStickyNote: StickyNote = response; for(let i = 0; i < this.stickyNo ...

Nested Tagged Union Types in Typescript

Imagine having the following types (syntax similar to Elm/Haskell): type Reply = LoginReply | LogoutReply type LoginReply = LoginSucceeded | AlreadyLoggedIn String When trying to represent this in Typescript using discriminated unions, a challenge arises ...

NGRX Angular does not support iteration of state.data

I'm attempting to combine state.data with payload.data but encountering an error: TypeError: state.data is not iterable This is my code snippet: on(apiActionGroup.success, (state, payload) => newState(state, { data: { [payload.page?.toStrin ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...

The error message "Identifier 'title' is not defined. '{}' does not contain such a member angular 8" indicates that the title variable is not recognized or defined in the

Here is the code snippet of my component: import { Router, ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { CategoriesService } from 'src/app/categories.service'; import { P ...

What are the steps to executing a function that instantiates an object?

Here is an object with filter values: const filters = ref<filterType>({ date: { value: '', }, user: { value: '', }, userId: { value: '', }, ... There is a data sending function that takes an obje ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...

Issue with Master Toggle functionality for checkbox within expanded rows of Mat-Table does not function correctly

I'm facing an issue with my multi-row expandable mat table grid where the master toggle for inner grid checkboxes is not working. Each row fetches data from different APIs on click, and I have a checkbox selection in every row for the inner grid. Int ...

Typescript and RxJS: Resolving Incompatibility Issues

In my development setup, I work with two repositories known as web-common and A-frontend. Typically, I use npm link web-common from within A-frontend. Both repositories share various dependencies such as React, Typescript, Google Maps, MobX, etc. Up until ...

Unit testing component in Ionic 2 with Ionic's specific markup and elements

Within my Angular 2 component for an Ionic 2 app, I utilize Ionic's markup as shown below: <ion-card> <h3>{{ rawcontent.name }}</h3> <p *ngIf="rawcontent.description">{{ rawcontent.description }}</p> </ion-car ...

What is the best way to incorporate TypeScript variables into CSS files?

In my Angular project, I am aiming to utilize a string defined in Typescript within a CSS file. Specifically, I want to set the background image of a navbar component using a path retrieved from a database service. Although I came across suggestions to use ...

Troubleshooting problem with TypeScript and finding/filtering operations

let access = environment.access.find(it => it.roleName == userRole); Property 'filter' does not exist on type '{ siteadmin: string[]; manager: string[]; employee: string[]; contractor: any[]; }'. This scenario should work perfectly ...