4

I come with a simplified question about TypeScript where my "key" and "value" are getting switched. To demonstrate the issue I have the following the map, which I store in file by itself:

Parts.ts

export const PART_DATA : Map<string, string> = new Map( 
[
    [ 'PI',  'Piping' ],
    [ 'TC',  'Truck Components' ],
    [ 'BE',  'Brake Equipment' ]
]);

... and we will call my other file where I implement this Map, ProcessParts.ts, which will look like so:

  import {Component, OnInit, NgModule} from '@angular/core';
  import {PART_DATA} from './Parts';    

  export class ProcessParts {

      ngOnInit(){    
        PART_DATA.forEach((key: string, value: string) => {
          console.log("here is " + key + ', ' + value);
        });
      }
  }

...and our output will begin to read like so:

here is Piping, PI  

... when the key and value should be swapped. It is not a huge problem, but I am using a couple maps set up like this PART_DATA example, but this is the first time I have seen this problem when I am iterating over this map (this this post on iterating iterating over a ts map). For clarity, I need to iterate over the Map in the first place so I can display some options to the UI.

1 Answer 1

6

The callback in the forEach method on Map takes arguments in the following order:

function(value,key,map)

The correct syntax would be:

 PART_DATA.forEach((value: string, key: string) => {
          console.log("here is " + key + ', ' + value);
        });

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.