首页 > 解决方案 > 使用数组的反向映射

问题描述

我有一组Map需要同时使用的数据;这是一个例子:

const mapping: Map<string, string> = new Map<string, string>([
    ['one', '1'],
    ['two', '2'],
    ['three', '3'],
    ['four', '4'],
]);

// I should eliminate this; I want to write it with single-line syntax
const reverseMapping: Map<string, string> = new Map<string, string>([
    ['1', 'one'],
    ['2', 'two'],
    ['3', 'three'],
    ['4', 'four'],
]);

const data = Array.from(mapping).map(e => e.reverse());

const reverseMap: Map<string, string> = new Map<string, string>([data])

我无法从语法上弄清楚如何做到这一点;我该怎么做?

https://stackblitz.com/edit/typescript-d7jocb

标签: javascripttypescript

解决方案


在运行时和编译器中都可以使用的单行器是这样的:

const flipMap = <K, V>(m: Map<K, V>) => new Map(Array.from(m, ([k, v]) => [v, k]));
// const flipMap: <K, V>(m: Map<K, V>) => Map<V, K>

对于您的特定地图,您可以这样做:

const reverseMapping = new Map(Array.from(mapping, ([k, v]) => [v, k])); 
// const reverseMapping: Map<string, string>

让我们测试一下:

console.log(mapping); // Map(4) { one → "1", two → "2", three → "3", four → "4" }
console.log(reverseMapping); // { 1 → "one", 2 → "two", 3 → "three", 4 → "four" }

在我看来很好。希望有帮助;祝你好运!

Playground 代码链接


推荐阅读