admin管理员组文章数量:1389813
I e 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.
I e 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
Reset to default 6The 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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
本文标签: javascriptTypeScript Map key and value swapped on iterationStack Overflow
版权声明:本文标题:javascript - TypeScript Map: key and value swapped on iteration - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744721746a2621734.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论